tags:

views:

114

answers:

2

I m sorry for a question like this. But i m not too sure about the difference of : 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 doenst the following work?

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

giving a type error.

+7  A: 

: conses an element onto a list.

++ appends two lists.

The former has type

a -> [a] -> [a]

whereas the latter has type

[a] -> [a] -> [a]
Brian
understood. Than you.
For the Lisp-vocabulary-challenged, "cons" constructs a new list node and adds it to the head of the list.
Nate C-K
+8  A: 

The : operator is known as the "cons" operator and is used to append a head element to a list. So [] is a list and x:[] is appending x to the empty list making a the list [x]. If you then cons y:[x] you end up with th elist [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.

Vincent Ramdhanie
Cool. thank you.