I’m at the moment reading the book “Real world functional programming”, and wondering how I can write something like:
let numbers = [ 1 .. 10 ]
let isOdd(n) = (n%2 = 1)
let square(n) = n * n
let myList =
numbers
|> List.map square
|> List.iter(printfn "%d")
|> List.filter isOdd
|> List.iter(printfn "%d")
The code I’ve posted will fail after the First List.iter() with a message that says:
Type mismatch. Expecting a unit ->
‘a but given a ‘b list -> ‘b
list The type ‘unit’ does not
match the type ”a list’
How can I do something like above (just where it will work)?
You could use
List.mapinstead ofList.iter, and return the elements unchanged. You would be rebuilding the list:Another way would be, to instead of storing each element separatly, is to store the whole list as a function parameter:
One last variant I can think of, is to completely branch the pipeline: