Lesson 11 of 15
Map & Filter
Map & Filter
List.map transforms every element:
let squares = List.map (fun x -> x * x) [1; 2; 3; 4; 5]
// [1; 4; 9; 16; 25]
List.filter keeps elements that satisfy a predicate:
let evens = List.filter (fun x -> x % 2 = 0) [1; 2; 3; 4; 5; 6]
// [2; 4; 6]
Combine them with the pipe operator:
let result =
[1..10]
|> List.filter (fun x -> x % 2 <> 0)
|> List.map (fun x -> x * x)
|> List.sum
// 1 + 9 + 25 + 49 + 81 = 165
Your Task
Write a function evenSquaresSum that takes a list of integers, keeps the even numbers, squares each, and returns the sum. Use pipes.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.