Skip to content

Instantly share code, notes, and snippets.

@mkmurray
Created February 6, 2012 07:16
Show Gist options
  • Save mkmurray/1750393 to your computer and use it in GitHub Desktop.
Save mkmurray/1750393 to your computer and use it in GitHub Desktop.
Fold in F# and C#
// 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);
(* 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