Lesson 14 of 15
Map and Filter
Higher-Order Functions: Map and Filter
Higher-order functions take other functions as arguments. Two of the most important are map and filter.
map applies a function to every element of a list:
#eval [1, 2, 3, 4, 5].map (fun x => x * 2)
-- [2, 4, 6, 8, 10]
filter keeps only elements that satisfy a predicate:
#eval [1, 2, 3, 4, 5, 6].filter (fun x => x % 2 == 0)
-- [2, 4, 6]
You can chain them together:
#eval [1, 2, 3, 4, 5, 6].filter (fun x => x % 2 == 0)
|>.map (fun x => x * x)
-- [4, 16, 36]
Your Turn
- Use
mapto square every element of[1, 2, 3, 4, 5] - Use
filterto keep only numbers greater than 3 from[1, 2, 3, 4, 5, 6]
Lean loading...
Loading...
Click "Run" to execute your code.