Type unification question with lists of tuples of strings
Someone joined #haskell
, and asked a fairly novice homework question. How do you sort two equal length lists of string tuples? In an attempt to help them - my Haskell sucks - I wrote this.
sortBy (\(x:y) (x':y') -> let { a = x `compare` x'; b = y `compare` y' } in if a == EQ then b else a ) $ let f (a,b) = a++b in f ( [("a", "b"), ("e", "b"), ("x", "b"), ("x", "g")], [("b", "c"),("b", "d"), ("g", "a"), ("g", "c")] )
I assume that's far from working. Why doesn't this work:
sortBy (\(x:y) (x':y') -> undefined) $ [("a","b"),("e","b"),("x","b"),("x","g"),("b","c"),("b","d"),("g","a"),("g","c")]
I get this error
<interactive>:1:67:
Couldn't match expected type `[t]'
against inferred type `([Char], [Char])'
In the expression: ("a", "b")
In the expression: [("a", "b"), ("e", "b"), ("x", "b"), ("x", "g")]
In the first argument of `f', namely
`([("a", "b"), ("e", "b")开发者_StackOverflow中文版, ("x", "b"), ("x", "g")],
[("b", "c"), ("b", "d"), ("g", "a"), ("g", "c")])'
I'd put these on multiple lines, but I'm not sure where I have to break them to make them work (Haskell whitespace is goofy).
SortBy has a type of sortBy :: (a -> a -> Ordering) -> [a] -> [a]
and my list has a type of [([Char], [Char])]
How come a
can't be unified with ([Char], [Char])
to make
sortBy :: (([Char], [Char]) -> ([Char], [Char]) -> Ordering) -> [([Char], [Char])] -> [([Char], [Char])]`
Try the next
sortBy (\(x,y) (x',y') -> let { a = x `compare` x'; b = y `compare` y' } in if a == EQ then b else a ) $ let f (a,b) = a++b in f ( [("a", "b"), ("e", "b"), ("x", "b"), ("x", "g")], [("b", "c"),("b", "d"), ("g", "a"), ("g", "c")] )
It looks like a typo for me. (:)
is a list constructor. Use (,) to construct a tuple
精彩评论