Wednesday, May 19, 2010

Pascal’s Triangle in F#

Fun with F# :)

let rec PascalsTriangle = seq { 
yield [1];
for aLine in PascalsTriangle ->
List.append (1::Seq.toList (Seq.map (fun (x,y) -> x+y) (Seq.pairwise aLine))) ([1])
}



> PascalsTriangle |> Seq.take 10 |> Seq.toList;;
val it : int list list =
[[1]; [1; 1]; [1; 2; 1]; [1; 3; 3; 1]; [1; 4; 6; 4; 1]; [1; 5; 10; 10; 5; 1];
[1; 6; 15; 20; 15; 6; 1]; [1; 7; 21; 35; 35; 21; 7; 1];
[1; 8; 28; 56; 70; 56; 28; 8; 1]; [1; 9; 36; 84; 126; 126; 84; 36; 9; 1]]
>


 



I actually started this with a pipe forward approach, but ( at least with my knowledge of the syntax) it seemed longer to write down.



let rec PascalsTriangle1 = seq { 
yield [1];
for aLine in PascalsTriangle1 ->
let
newLine =
aLine
|> Seq.pairwise
|> Seq.map (fun (x,y) -> x+y)
|> Seq.toList
List.append (1::newLine) [1]
}

No comments: