将列表中的相邻元素放入元组

时间:2018-03-19 10:38:38

标签: haskell purescript

给出元素列表:

xs = [a, b, c, d, ... z]

其中a, b, c等是任意值的占位符。 我想实现一个产生

的函数adjacents :: [a] -> [(a, a)]
adjacentValues = [(a, b), (b, c), (c, d), ... (y, z)]

在Haskell中,递归定义相当简洁:

adjacents :: [a] -> [(a, a)]
adjacents (x:xs) = (x, head xs) : adjacents xs
adjacents [] = []

Purescript更加冗长:

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(使用折叠)?

免责声明:此问题同时包含Purescript和Haskell标签,因为我想向更广泛的受众群体开放。我认为答案不依赖于haskells懒惰评估语义,因此在两种语言中都有效。

5 个答案:

答案 0 :(得分:7)

在Haskell中,没有显式递归,你可以用它的尾部压缩列表。

   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)]

答案 1 :(得分:2)

完整性的Purescript解决方案:

adjacent :: forall n. List n -> List (Tuple n n)
adjacent list = zip list $ fromMaybe empty $ tail list

可以更优雅地表达为:

adjacent :: forall n. List n -> List (Tuple n n)
adjacent list = zip list $ drop 1 list

答案 2 :(得分:0)

为了便于说明(基于zip的解决方案肯定更好),这里是您明确递归的Haskell解决方案。我没有特别的原因把它打成一个单线。

{-# LANGUAGE LambdaCase #-}

import Data.List (unfoldr)

adjacent :: [a] -> [(a, a)]
adjacent = unfoldr (\case { x:y:ys -> Just ((x, y), ys); _ -> Nothing })

(请注意,此处的模式匹配处理列表,其中包含奇数个元素而不会崩溃。)

答案 3 :(得分:0)

自从我们看到zipunfoldr后,我们应该使用foldr

adjacent :: [a] -> [(a,a)]
adjacent xs = foldr go (const []) xs Nothing
  where
    go a r Nothing = r (Just a)
    go a r (Just prev) = (prev, a) : r (Just a)

现在,因为每个玩具问题都需要一个过度设计的解决方案,这就是你可以用来获得双面列表融合的方法:

import GHC.Exts (build)

adjacent :: [a] -> [(a,a)]
adjacent xs = build $ \c nil ->
  let
    go a r Nothing = r (Just a)
    go a r (Just prev) = (prev, a) `c` r (Just a)
  in foldr go (const nil) xs Nothing
{-# INLINE adjacent #-}

答案 4 :(得分:0)

折叠状态,其中状态是最后配对的项目:

在Haskell:

import Data.List (mapAccumL)

adjacents :: [a] -> [(a, a)]
adjacents [] = []
adjacents (x:xs) = snd $ mapAccumL op x xs
    where
        op x y = (y, (x,y))