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

后端 未结 1 960
北恋
北恋 2021-01-14 21:43

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         


        
相关标签:
1条回答
  • 2021-01-14 22:23

    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
    
    0 讨论(0)
提交回复
热议问题