19 people like it.

Pascal's Triangle

This code sample generates Pascal's triangle as jagged 2D list (list of lists).

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
// Generate n rows of Pascal's Triangle
let pascal n = 
  let rec pas L n =
    if n = 0 then L
    else
      let A::t = L in
      pas (((1::[for i in 1..(List.length A-1) -> A.[i-1]+A.[i]])@[1])::L) (n-1)
  pas [[1;1]] n

// Create Pascal's Triangle with 10 rows
pascal 10;;
val pascal : n:int -> int list list

Full name: Script.pascal
val n : int
val pas : (int list list -> int -> int list list)
val L : int list list
val A : int list
val t : int list list
val i : int
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val length : list:'T list -> int

Full name: Microsoft.FSharp.Collections.List.length
Raw view New version

More information

Link:http://fssnip.net/23
Posted:6 years ago
Author:Dmitry Soshnikov
Tags: lists , jagged array , algorithms , learning f#