How do you write the function 'pairs' in Haskell?

独自空忆成欢 提交于 2019-12-20 17:31:36

问题


The pairs function needs to do something like this:

pairs [1, 2, 3, 4] -> [(1, 2), (2, 3), (3, 4)]

回答1:


pairs [] = []
pairs xs = zip xs (tail xs)



回答2:


You could go as far as

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

but

pairs xs = zip xs (tail xs)

is probably clearer.




回答3:


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". This is because y doubles as both the second element of the current pair and the first element of the next. Otherwise we'd have to make a special case for lists of length 1.

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



回答4:


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]


来源:https://stackoverflow.com/questions/2546524/how-do-you-write-the-function-pairs-in-haskell

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