83 people like it.

Composing a list of functions

Composition of functions in F# is easily achieved by using the >> operator. You can also chain an arbitary amount of functions (represented as a list or sequence) together by folding the list/seq with >>. [More formally: the set of endomorphisms 'a -> 'a forms a monoid with the binary, associative operator ">>" (or "<<") and the neutral element "id".]

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
// compose a list of functions fs into a single function
let compose fs = List.reduce (>>) fs

// apply list of functions to an initial arg
let fs = [(*) 2; (+) 7; (*) 3; (+) 3]
compose fs 3
// = 3 |> ((*)2 >> (+)7 >> (*)3 >> (+) 3)
// = 3 |> (*)2 |> (+)7 |> (*)3 |> (+) 3
// = (((3 * 2) + 7) * 3) + 3
// = 42
val compose : fs:('a -> 'a) list -> ('a -> 'a)

Full name: Script.compose
val fs : ('a -> 'a) list
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val reduce : reduction:('T -> 'T -> 'T) -> list:'T list -> 'T

Full name: Microsoft.FSharp.Collections.List.reduce
val fs : (int -> int) list

Full name: Script.fs

More information

Link:http://fssnip.net/S
Posted:13 years ago
Author:Novox
Tags: fold , reduce , compose , function composition , monoid