4 people like it.

n-ary Seq.map (Numerals)

A pattern for creating n-ary Seq.map functions, based on numerals.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
// For more info: ftp://ftp.cs.au.dk/pub/BRICS/RS/01/10/BRICS-RS-01-10.pdf

let (<*>) fs xs = Seq.map2 (fun f x -> f x) fs xs
let succ n fs xs = n (fs <*> xs)
let map n f = n (Seq.initInfinite (fun _ -> f))

// Numerals
let ``1``<'a1, 'r> : seq<('a1 -> 'r)> -> seq<'a1> -> seq<'r> = 
    succ id
let ``2``<'a1, 'a2, 'r> : seq<('a1 -> 'a2 -> 'r)> -> seq<'a1> -> seq<'a2> -> seq<'r> = 
    succ ``1``
let ``3``<'a1, 'a2, 'a3, 'r> : seq<('a1 -> 'a2 -> 'a3 -> 'r)> -> seq<'a1> -> seq<'a2> -> seq<'a3> -> seq<'r> = 
    succ ``2``

// Examples
map ``1`` (fun x -> x + 1) [1; 2] // [2; 3]
map ``2`` (fun x y -> x + y) [1; 2] [1; 2] // [2; 4]
map ``3`` (fun x y z -> x + y + z) [1; 2] [1; 2] [1; 2] // [3; 6]
val fs : seq<('a -> 'b)>
val xs : seq<'a>
module Seq

from Microsoft.FSharp.Collections
val map2 : mapping:('T1 -> 'T2 -> 'U) -> source1:seq<'T1> -> source2:seq<'T2> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map2
val f : ('a -> 'b)
val x : 'a
val succ : n:(seq<'a> -> 'b) -> fs:seq<('c -> 'a)> -> xs:seq<'c> -> 'b

Full name: Script.succ
val n : (seq<'a> -> 'b)
val fs : seq<('c -> 'a)>
val xs : seq<'c>
val map : n:(seq<'a> -> 'b) -> f:'a -> 'b

Full name: Script.map
val f : 'a
val initInfinite : initializer:(int -> 'T) -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.initInfinite
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val id : x:'T -> 'T

Full name: Microsoft.FSharp.Core.Operators.id
val x : int
val y : int
val z : int

More information

Link:http://fssnip.net/9X
Posted:5 years ago
Author:Nick Palladinos
Tags: seq , map , zipwith , applicative functor