Swap the first two element of a list, (Haskell)

拈花ヽ惹草 提交于 2020-01-21 09:10:10

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/15736698/swap-the-first-two-element-of-a-list-haskell

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