Skip to content

Instantly share code, notes, and snippets.

@ntreu14
Last active October 20, 2017 19:16
Show Gist options
  • Save ntreu14/21af74c4c71b17de75e75131d43157d4 to your computer and use it in GitHub Desktop.
Save ntreu14/21af74c4c71b17de75e75131d43157d4 to your computer and use it in GitHub Desktop.
Different ways to implement a filter then map
let isEven num = num % 2 = 0
let square num = num * num
let printResults = List.iter <| printfn "%d"
// Filter then map
[1..5]
|> List.filter isEven
|> List.map square
|> printResults
// Filter then map using `fold`
let foldFn predicate mapFn state = function
| i when predicate i -> state @ [mapFn i]
| _ -> state
[1..5]
|> List.fold (foldFn isEven square) []
|> printResults
// Filter then map using function composition
let filterMap predicate mapFn =
List.filter predicate >> List.map mapFn
[1..5]
|> filterMap isEven square
|> printResults
// Implement map then filter using fold, just for fun :)
let mapFilter mappingFn predicate state current =
let mappedResult = mappingFn current
match predicate mappedResult with
| true -> state @ [mappedResult]
| false -> state
[1..5]
|> List.fold (mapFilter square isEven) []
|> printResults
// These outputs should match those above
[1..5]
|> List.map square
|> List.filter isEven
|> printResults
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment