Haskell:将列表拆分为3元组

Haskell:将列表拆分为3元组,haskell,Haskell,了解Haskell(单子等)的基本原理,但没有使用过 两年来,我一直在努力两个小时来干净利落地做这个小练习: 我想将一行3*n整数(如“1 1 2 2 3 3”)转换为Int(如[(1,1,1),(2,2,2),(3,3,3)]的3元组列表 这应该以一种直接的错误捕捉方式来完成 到目前为止,我能想到的最佳解决方案包括: groupsOf3 :: [a] -> Maybe [(a,a,a)] groupsOf3 list = let fun l = case l of

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

我想将一行3*n整数(如
“1 1 2 2 3 3”
)转换为
Int
(如
[(1,1,1),(2,2,2),(3,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

这对我来说似乎不太优雅。我如何将这个函数(同一个接口)编码到这个点?

我实际上认为你的解决方案看起来很不错。但是,因为我不能抵抗选择颜色,你也可以考虑这样的事情:

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

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