[Haskell-cafe] where to put handy functions?
Brent Yorgey
byorgey at gmail.com
Thu Aug 9 17:40:15 EDT 2007
On 8/9/07, Chad Scherrer <chad.scherrer at gmail.com> wrote:
>
>
> extract :: [Int] -> [a] -> [a]
> extract = f 0
> where
> f _ _ [] = []
> f _ [] _ = []
> f k nss@(n:ns) (x:xs) = if n == k then x:f (k+1) ns xs
> else f (k+1) nss xs
>
> This behaves roughly as
> extract ns xs == map (xs !!) ns
>
> except that it's a lot more efficient, and it still works if ns or xs
> (but not both) are infinite. Oh, and "ns" are required to be ordered
> and non-negative.
Nifty function there. =) And for the record, it works just fine if both
lists are infinite -- it just produces an infinite output list, but it's
lazy so no problem:
*Main> take 10 $ extract [1,3..] [2..]
[3,5,7,9,11,13,15,17,19,21]
-Brent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070809/40767bd3/attachment.htm
More information about the Haskell-Cafe
mailing list