How to use groupBy and zip in real practice?
import Data.List.Split
import Data.List(nub, groupBy)
z = splitOn "+" "x^2+2*x^3+x^2"
y = map (splitOn "*") z
x = map head y
toInt :: [String] -> [Int]
toInt = map read
u1 = filter ((< 2) . length) y
u2 = filter ((> 1) . length) y
v = map ("1" :) u1
q = u2 ++ v
q2 = zip toInt(map head q) (map last q)
q6 = groupBy nub(map tail q) q
q3 = map tail q
q5 = nub(q3)
q1 = map head q
1. For
zip toInt(map head q) (map last q)
I would like to add back the head to the tail after convert head int开发者_C百科o integer
result should be [[1,"x^3"],[2,"x^2"],[1,"x^2"]]
I can do
*Main Data.List> zip [2,1,1] ["x^3","x^2","x^2"]
[(2,"x^3"),(1,"x^2"),(1,"x^2")]
but above can not, and there is a difference I noticed is, this is ()
, not []
2. How to write groupBy
on a list, I have passed distinct elements for groupBy
After grouping, it is for adding their head
groupBy (nub(map tail q)) q
:1:10:
Couldn't match expected type a0 -> a0 -> Bool'
with actual type
[a1]'
In the return type of a call of nub'
In the first argument of
groupBy', namely `(nub (map tail q))'
In the expression: groupBy (nub (map tail q)) q
q is like a hash table, it seems that it can not group by second element
One issue is that zip toInt(map q) (map last q)
isn't getting parsed the way you think it is.
Unlike languages with C-style syntax, haskell parses the above as
zip toInt (map head q) (map last q)
(Note the space).
That is, it's not applying toInt
to the result of map head q
the way you want it to. Instead, it's attempting to do zip toInt (map head q)
, which will give you a type error, since you're zipping a function and a list.
What you want instead is
zip (toInt (map head q)) (map last q)
Or slightly more succinctly
zip (toInt $ map head q) (map last q)
As for your second issue, you're having a similar issue with syntax. Also, the first argument to groupBy
needs to be a function that determines equality for the purposes of creating groups.
精彩评论