Created
February 6, 2012 07:16
-
-
Save mkmurray/1750393 to your computer and use it in GitHub Desktop.
Fold in F# and C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// FuncList is a functional "cons" list type with Head value and Tail list | |
public R Fold<T, R>(this FuncList<T> list, Func<R, T, R> func, R init) { | |
if (list.IsEmpty) { | |
return init; | |
} | |
else { | |
var foldState = func(init, list.Head); | |
return list.Tail.Fold(func, foldState); | |
} | |
} | |
var list = FuncList.Cons(1, | |
FuncList.Cons(2, | |
FuncList.Cons(3, | |
FuncList.Cons(4, | |
FuncList.Cons(5, | |
FuncList.Empty<int>()))))); | |
list.Fold((x,y) => x * y, 1); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* Recursive let binding *) | |
let rec fold f init list = | |
match list with | |
| [] -> init | |
| head::tail -> | |
let foldState = f init head | |
fold f foldState tail | |
[ 1 .. 5 ] |> fold (*) 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment