简体   繁体   English

Haskell组预定义的长度没有显式递归

[英]Haskell group predefined length no explicit recursion

How can I make a function that groups element of a list into lists of predefined length without using explicit recursion. 如何创建一个函数,将列表的元素分组为预定义长度的列表,而不使用显式递归。

For example, for 2: 例如,2:

[1, 2, 3, 4, 5, 6, 7, 8]
[[1, 2], [3, 4], [5, 6], [7, 8]]

Thank you! 谢谢!

The following would work (though you may consider it cheating to use groupBy from Data.List) 以下是可行的(尽管你可能会认为从Data.List使用groupBy作弊)

import Data.Function (on)
import Data.List     (groupBy)

group :: Int -> [a] -> [[a]]
group n = map (map snd)
        . groupBy ((==) `on` fst)
        . zip (enumFrom 1 >>= replicate n)

This is a one-liner if you set your wrap at 100 characters :). 如果你将你的包裹设置为100个字符,这是一个单行的:)。 I'm guessing you are looking for something that uses a fold. 我猜你正在寻找一种使用折叠的东西。

group :: Int -> [a] -> [[a]]
group n = uncurry (:) . foldr (\x (l,r) -> if length l == n then ([x],l:r) 
                                                            else (x:l,r))
                              ([],[])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM