Monday, December 3, 2012

list comprehensions

(In learning from "Programming F# 3.0, 2nd Edition")

F#'s List, Sequence and so forth can comprehend any functions to define its elements.
> let greetingsTo who = ["Hello, " + who; "Goodbye, " + who];;

val greetingsTo : who:string -> string list

> greetingsTo "Mr.Lawrence";;
val it : string list = ["Hello, Mr.Lawrence"; "Goodbye, Mr.Lawrence"]

Using for clause with yield can define values iteratively.
> let squaringOddNums = [ for i in 1..2..11 do yield i * i ];;

val squaringOddNums : int list = [1; 9; 25; 49; 81; 121]

And, you can the notation -> instead of do yield.
> let squaringOddNums = [ for i in 1..2..11 -> i * i ];;

val squaringOddNums : int list = [1; 9; 25; 49; 81; 121]

But, as you may notice, some cases is simpler to use List.map than to use list comprehensions.
> List.map (fun i -> i * i) [1..2..11];;
val it : int list = [1; 9; 25; 49; 81; 121]

No comments:

Post a Comment