【问题标题】:Haskell: split list into 3-tuplesHaskell:将列表拆分为 3 元组
【发布时间】:2013-05-25 01:42:26
【问题描述】:

了解 Haskell 的基本原理(Monads 等),但没有使用过 2年来,我一直在努力两个小时来干净地做这个小练习:

我想将一行 3*n 整数(如"1 1 1 2 2 2 3 3 3")转换为Int 的三元组列表(如[(1,1,1),(2,2,2),(3,3,3)]

这应该以一种直截了当、能捕捉错误的方式来完成。

到目前为止,我能想到的最佳解决方案包含以下内容:

groupsOf3 :: [a] -> Maybe [(a,a,a)]
groupsOf3 list =
    let fun l = case l of
            []           -> []
            (x:y:z:rest) -> (Just (x,y,z)) : (fun rest)
            _            -> [Nothing]
    in sequence $ fun list

这对我来说似乎并不优雅。我如何更切题地编写这个函数(使用相同的接口)?

【问题讨论】:

    标签: haskell


    【解决方案1】:

    我实际上认为您的解决方案看起来不错。但是,因为我无法抗拒选择棚色,您也可以考虑这样的事情:

    import Control.Applicative
    import Control.Monad
    groupsOf3 (x:y:z:rest) = ((x,y,z):) <$> groupsOf3 rest
    groupsOf3 smallList    = guard (null smallList) >> return []
    

    你也可以考虑使用chunksOf:

    import Control.Monad
    import Data.List.Split
    convert [x,y,z] = Just (x,y,z)
    convert _ = Nothing
    groupsOf3 = sequence . map convert . chunksOf 3
    

    【讨论】:

    • mapM convert . chunksOf 3
    猜你喜欢
    • 2011-11-16
    • 2019-06-05
    • 2019-10-20
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多