What is the difference between ++ and : in haskell?

烈酒焚心 提交于 2019-12-10 16:01:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!