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.
What's the difference between (>>) and (*>) in Haskell? They do exactly the same thing. >> is specialized to Monad while *> to Applicative .
The ++ operator is the list concatenation operator which takes two lists as operands and "combine" them into a single list.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With