Tuesday, 30 March 2010

Generic Monadic Map and Join using statically resolved type variables



let inline mapM b f m =       
    let unit x    = (^x: (member Return: ^b -> ^n) b, x)  
    let (>>=) m f = (^x: (member Bind: ^m -> (^a -> ^n) -> ^n) b, m, f)
    m >>= (fun x -> unit (f x))


let inline joinM b m =          
    let (>>=) m f = (^x: (member Bind: ^m -> (^n -> ^n) -> ^n) b, m, f)
    m >>= id

Friday, 12 March 2010

SplitEvery (chunk)



open System
open System.Collections.Generic
open System.Linq

//splitEvery :: Int -> [a] -> [[a]]
let splitAt n (xs:IEnumerable<'a>) = (xs.Take n, xs.Skip n)

let rec splitEvery n xs =
    let (ks, vs) = splitAt n xs in
    seq { yield ks
          yield! splitEvery n vs }