Is there a nicer way to do this?

segment :: Int -> [a] -> [[a]] segment 0 _ = [] segment _ [] = [] segment n x = (take n x) : segment n (drop n x) I did a version of this which used splitAt but I wasn't sure whether it was going to buy me anything re performance that would justify its ugliness. Michael

mfeathers:
segment :: Int -> [a] -> [[a]] segment 0 _ = [] segment _ [] = [] segment n x = (take n x) : segment n (drop n x)
The first set of parens can go, segment n x = take n x : segment n (drop n x)
I did a version of this which used splitAt but I wasn't sure whether it was going to buy me anything re performance that would justify its ugliness.
Besides, splitAt n xs = (take n xs, drop n xs) -- Don

On Sun, Jul 6, 2008 at 16:45, Michael Feathers
segment :: Int -> [a] -> [[a]] segment 0 _ = [] segment _ [] = [] segment n x = (take n x) : segment n (drop n x)
I did a version of this which used splitAt but I wasn't sure whether it was going to buy me anything re performance that would justify its ugliness.
You can use segment n = takeWhile (not . null) . unfoldr (Just . splitAt n) I don't know how it compares in performance. It's from http://www.haskell.org/haskellwiki/Blow_your_mind - John

On Sun, Jul 6, 2008 at 5:25 PM, John Hamilton
On Sun, Jul 6, 2008 at 16:45, Michael Feathers
wrote: segment :: Int -> [a] -> [[a]] segment 0 _ = [] segment _ [] = [] segment n x = (take n x) : segment n (drop n x)
I did a version of this which used splitAt but I wasn't sure whether it was going to buy me anything re performance that would justify its ugliness.
You can use
segment n = takeWhile (not . null) . unfoldr (Just . splitAt n)
I don't know how it compares in performance. It's from http://www.haskell.org/haskellwiki/Blow_your_mind
Watch out for negative numbers, though.
participants (4)
-
Don Stewart
-
Evan Laforge
-
John Hamilton
-
Michael Feathers