In order to swap the first two elements of a list, I've written the following code:
swap_first_two_elements :: [a]->[a]
swap_first_two_elements list=case list of
x:y:_ -> y:x:_
[x] -> Nothing
[]-> Nothing
However, the terminal shows the error shown below:
[1 of 1] Compiling Main ( test.hs, interpreted )
test.hs:3:16: Pattern syntax in expression context: _
Failed, modules loaded: none.
Prelude>
Who likes to tell me what is wrong with it?
Btw, ive also tried to combine the last two row into:
[x] || [] ->Nothing
How is it wrong? Terminal shows:
test.hs:4:3: Parse error in pattern: [x] || []
Failed, modules loaded: none.
Who likes to tell me what is wrong with it? Thanks XD
The mistake is that you cannot use _
in the result of a branch. _
is reserved to indicate an unused variable. If you want to reuse the tail of the list, you must bind it to another name:
swap_first_two_elements :: [a]->[a]
swap_first_two_elements list = case list of
x:y:xs -> y:x:xs
[x] -> Nothing
[] -> Nothing
However, if you compile that you will get another error. Your case branches return values of different types. The first branch returns a value of type [a]
, but your second and third branch return a value of type Maybe [a]
. To fix it, you have to wrap the first branch in a Just
(and also fix your type signature to indicate that you are returning Maybe [a]
and not [a]
):
swap_first_two_elements :: [a] -> Maybe [a]
swap_first_two_elements list = case list of
x:y:xs -> Just (y:x:xs)
[x] -> Nothing
[] -> Nothing
The last improvement is that you can combine your last two case branches into one by using the fallback pattern match on everything:
swap_first_two_elements :: [a] -> Maybe [a]
swap_first_two_elements list = case list of
x:y:xs -> Just (y:x:xs)
_ -> Nothing