Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell (:) and (++) differences

I'm sorry for a question like this. I'm not too sure about the difference of the : and ++ operator in Haskell.

x:y:[] = [x,y]   

also

[x] ++ [y] = [x,y] 

as for the reverse function which arose this question for me,

reverse ::[a]->[a] reverse [] = [] reverse (x:xs) = reverse(xs)++[x] 

Why doesn't the following work?

reversex ::[Int]->[Int] reversex [] = [] reversex (x:xs) = reversex(xs):x:[] 

giving a type error.

like image 571
DarthVader Avatar asked Nov 30 '09 04:11

DarthVader


People also ask

What's the difference between and in Haskell?

What's the difference between (>>) and (*>) in Haskell? They do exactly the same thing. >> is specialized to Monad while *> to Applicative .

What does ++ mean in Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combine" them into a single list.

Why is Haskell so powerful?

Haskell's design is centered around pure functions and immutable data. Over and over, these features have proven essential for writing correct software. Managing global state, mutable data, and side effects is error-prone, and Haskell gives the programmer all the tools to avoid or minimize these sources of complexity.

What makes Haskell different from the languages that came before it?

Unlike other strongly typed languages types in Haskell are automatically inferred. This means that you very rarely have to declare the types of your functions, except as a means of code documentation.


1 Answers

The : operator is known as the "cons" operator and is used to prepend a head element to a list. So [] is a list and x:[] is prepending x to the empty list making a the list [x]. If you then cons y:[x] you end up with the list [y, x] which is the same as y:x:[].

The ++ operator is the list concatenation operator which takes two lists as operands and "combine" them into a single list. So if you have the list [x] and the list [y] then you can concatenate them like this: [x]++[y] to get [x, y].

Notice that : takes an element and a list while ++ takes two lists.

As for your code that does not work.

reversex ::[Int]->[Int] reversex [] = [] reversex (x:xs) = reversex(xs):x:[] 

The reverse function evaluates to a list. Since the : operator does not take a list as its first argument then reverse(xs):x is invalid. But reverse(xs)++[x] is valid.

like image 160
Vincent Ramdhanie Avatar answered Oct 01 '22 13:10

Vincent Ramdhanie