[Haskell-cafe] How to take a minimum sub list that only contain certain number of elements of certain type?

Gwern Branwen gwern0 at gmail.com
Tue Sep 25 19:56:48 CEST 2012


On Tue, Sep 25, 2012 at 1:42 PM, Rishabh Jain <rishabh11 at live.com> wrote:
> f x 0 = []
> f (x:xs) y | x `mod` 2 == 0 = x : (f xs y) | otherwise = x : (f xs (y-1))
>
>> f [0..] 4
>> [0,1,2,3,4,5,6,7]

Tsk, tsk. So ugly. How's this:

> let f x = take x . filter odd
>
> f 4 [0..]
~> [1, 3, 5, 7]

Notice that 0 is excluded, since 0 is *even*, not odd:
http://en.wikipedia.org/wiki/Parity_of_zero
If this is a serious problem, one can always just prepend zero:

> 0 : f 4 [1..]
~> [0, 1, 3, 5, 7]

-- 
gwern
http://www.gwern.net



More information about the Haskell-Cafe mailing list