简体   繁体   English

你如何在Haskell中编写函数'pair'?

[英]How do you write the function 'pairs' in Haskell?

对函数需要做这样的事情:

pairs [1, 2, 3, 4] -> [(1, 2), (2, 3), (3, 4)]
pairs [] = []
pairs xs = zip xs (tail xs)

You could go as far as 你可以走得那么远

import Control.Applicative (<*>)
pairs = zip <*> tail

but

pairs xs = zip xs (tail xs)

is probably clearer. 可能更清楚。

Just for completeness, a more "low-level" version using explicit recursion: 仅仅为了完整性,使用显式递归的更“低级”版本:

pairs (x:xs@(y:_)) = (x, y) : pairs xs
pairs _          = []

The construct x:xs@(y:_) means "a list with a head x , and a tail xs that has at least one element y ". 构造x:xs@(y:_)表示“具有头部x的列表,以及具有至少一个元素y的尾部xs ”。 This is because y doubles as both the second element of the current pair and the first element of the next. 这是因为y既可以作为当前对的第二个元素,也可以作为下一个元素的第一个元素。 Otherwise we'd have to make a special case for lists of length 1. 否则,我们必须为长度为1的列表创建一个特例。

pairs [_] = []
pairs []  = []
pairs (x:xs) = (x, head xs) : pairs xs

Call to the Aztec god of consecutive numbers: 打电话给连续数字的阿兹特克神:

import Control.Monad (ap)
import Control.Monad.Instances() -- for Monad ((->) a)

foo = zip`ap`tail $ [1,2,3,4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM