问题
I don't get this--
Prelude> "hi"++"there"
"hithere"
Prelude> "hi":"there"
<interactive>:12:6:
Couldn't match expected type `[Char]' with actual type `Char'
Expected type: [[Char]]
Actual type: [Char]
In the second argument of `(:)', namely `"there"'
In the expression: "hi" : "there"
Prelude>
Why doesn't that also return "hithere"?
回答1:
The types. Try this in GCHi:
Prelude> :t (:)
(:) :: a -> [a] -> [a]
Prelude. :t (++)
(++) :: [a] -> [a] -> [a]
回答2:
I get it now. The first operator needs to be an element, not a list.
So if i did 'h':"ithere"
it would return "hithere"
回答3:
The operator :
is one of the constructors for lists. So "hello"
is 'h':'e':'l':'l':'o':[]
. You can imagine lists being defined like: (not real haskell syntax)
data List a = (:) a (List a) | []
:
constructs a list by taking an element and a list. That's why the type is a->[a]->[a]
.
++
which concatenates lists is defined by using :
as a primitive:
(++) :: [a] -> [a] -> [a]
(++) [] ys = ys
(++) (x:xs) ys = x : xs ++ ys
来源:https://stackoverflow.com/questions/11569650/what-is-the-difference-between-and-in-haskell