27 people like it.

Make a chain of functions

Function composition can be done by using >> operator. The snippet at http://fssnip.net/S is a wonderful sample. But that version generates a function which is not easy when you want to debug. This version is to use pipeline (|>) operator.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
/// composite a function f with passing parameter a n times.
/// f: function
/// a: a is the parameter into f
/// n: composite the f n times

let composite f a n =
    [1..n] 
    |> Seq.map (fun _ -> f) 
    |> Seq.fold (fun acc n -> acc |> n) a
val composite : f:('a -> 'a) -> a:'a -> n:int -> 'a

Full name: Script.composite


 composite a function f with passing parameter a n times.
 f: function
 a: a is the parameter into f
 n: composite the f n times
val f : ('a -> 'a)
val a : 'a
val n : int
module Seq

from Microsoft.FSharp.Collections
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map
val fold : folder:('State -> 'T -> 'State) -> state:'State -> source:seq<'T> -> 'State

Full name: Microsoft.FSharp.Collections.Seq.fold
val acc : 'a
val n : ('a -> 'a)
Raw view Test code New version

More information

Link:http://fssnip.net/9m
Posted:13 years ago
Author:Tao Liu
Tags: compose , functions