交换列表的前两个元素,(Haskell) [英] Swap the first two element of a list, (Haskell)

查看:90
本文介绍了交换列表的前两个元素,(Haskell)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了交换列表的前两个元素,我编写了以下代码:

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

怎么了?终端显示:

test.hs:4:3: Parse error in pattern: [x] || []
Failed, modules loaded: none.

谁愿意告诉我这是怎么回事?谢谢XD

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

但是,如果进行编译,则会出现另一个错误.您的case分支返回不同类型的值.第一个分支返回类型为[a]的值,但是第二和第三个分支返回类型为Maybe [a]的值.要解决此问题,您必须将第一个分支包装在Just中(并修复类型签名以指示您返回的是Maybe [a]而不是[a]):

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

最后一个改进是,您可以通过对所有内容使用后备模式匹配将最后两个case分支合并为一个:

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

这篇关于交换列表的前两个元素,(Haskell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆