Skip to content

Instantly share code, notes, and snippets.

@PatrickMcDonald
Created September 12, 2014 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatrickMcDonald/bb374da501b8e1df1a6a to your computer and use it in GitHub Desktop.
Save PatrickMcDonald/bb374da501b8e1df1a6a to your computer and use it in GitHub Desktop.
let rec foldWhere (f:'State -> 'T -> 'State) acc p list =
match list with
| [] -> acc
| head::tail ->
let acc = if p head then (f acc head) else acc
foldWhere f acc p tail
//let countWhere<'T> = foldWhere (fun s (x:'T) -> s + 1) 0
let countWhere p l = List.fold (fun s x -> if p x then s + 1 else s) 0 l
countWhere ((>) 5) [1..100];;
countWhere (fun x -> x.ToString().Contains("1")) [1..100];;
List.filter (fun x -> x.ToString().Contains("1")) [1..100];;
List.fold (fun s x -> if x.ToString().Contains("1") then s + 1 else s) 0 [1..100]
(*
How about a foldWhere function with signature
foldWhere :
f:('State -> 'T -> 'State) ->
acc:'State -> p:('T -> bool) -> C<'T> -> 'State
You can get countWhere from this with
let countWhere<'T> = foldWhere (fun s (x:'T) -> s + 1) 0
Of course then we'll need foldRightWhere, scanWhere, reduceWhere, ...
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment