将列表中的相邻元素放入元组 [英] Put adjacent elements in List into Tuples
问题描述
给出一个元素列表:
xs = [a, b, c, d, ... z]
其中 a,b,c
等是任意值的占位符.我想实现一个功能 adjacents :: [a]->[(a,a)]
产生
where a, b, c
etc are placeholders for arbitrary values.
I want to implement a function adjacents :: [a] -> [(a, a)]
that produces
adjacentValues = [(a, b), (b, c), (c, d), ... (y, z)]
在Haskell中,递归定义相当简洁:
In Haskell, a recursive definition is reasonably concise:
adjacents :: [a] -> [(a, a)]
adjacents (x:xs) = (x, head xs) : adjacents xs
adjacents [] = []
Purescript稍微冗长一些:
Purescript is a little more verbose:
adjacents :: forall a. List a -> List (Tuple a a)
adjacents list = case uncons list of
Nothing -> []
Just {head: x, tail: xs} -> case head xs of
Just next -> Tuple x next : adjacents xs
Nothing -> []
有没有一种方法可以表达 adjacents
而无需显式递归(使用折叠)?
Is there a way to express adjacents
without explicit recursion (using a fold)?
免责声明:这个问题同时具有Purescript和Haskell标签,因为我想向更多的读者开放.我认为答案不取决于haskells惰性评估语义,因此在两种语言中均有效.
Disclaimer: This question has both Purescript and Haskell tags because I want to open it to a broader audience. I reckon an answer not to depend on haskells lazy-evaluation semantics, and therefore to be valid in both languages.
推荐答案
在Haskell中,无需显式递归,您可以使用列表尾部压缩列表.
In Haskell, without explicit recursion, you can zip a list with its tail.
let a = [1,2,3,4,5,6,7,8,9,0]
a `zip` tail a
=> [(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,0)]
这篇关于将列表中的相邻元素放入元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!