13 people like it.

Pascal's Triangle (2)

This code sample generates Pascal's triangle as jagged 2D list (list of lists). It takes 0.5 sec to generate 3000 rows (vs 16 sec for http://fssnip.net/23). Tip: try to avoid of using "list1 @ list2" construction.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
let pascal n = 
  let rec nextrow row y ys =
    match row with
    | x::xs -> nextrow xs x ((x + y)::ys)
    | [] -> 1::ys
  let rec addrow i z zs = 
    if i <= 1 then z::zs
    else addrow (i-1) (nextrow z 0 []) (z::zs)
  addrow n [1] [] 
val pascal : n:int -> int list list

Full name: Script.pascal
val n : int
val nextrow : (int list -> int -> int list -> int list)
val row : int list
val y : int
val ys : int list
val x : int
val xs : int list
val addrow : (int -> int list -> int list list -> int list list)
val i : int
val z : int list
val zs : int list list
Raw view Test code New version

More information

Link:http://fssnip.net/2b
Posted:13 years ago
Author:Shamil Sayfutdinov
Tags: lists , jagged array , algorithms , learning f#