anon_swe
anon_swe

Reputation: 9345

Pascal's Triangle in SML

I'm trying to write a function of the type:

pascal : int * int -> int

where the pair of ints represent the row and column, respectively, of Pascal's triangle.

Here's my attempt:

fun pascal(i : int, j : int) : int =
    if (i = 0 andalso j = 0) orelse i = j orelse i = 0
        then 1
    else
        pascal(i - 1, j - 1) + pascal(i - 1, j);

It works for my base cases but gives me strange output otherwise. For instance:

pascal(4, 2) gives me 11 and pascal(4, 1) gives me 15

It's a bit strange because, as long as the if clause fails and the else gets evaluated, I do want to return the sum of the element one row above and the element one row above and one element to the left.

What am I doing wrong?

Upvotes: 0

Views: 836

Answers (1)

mrmcgreg
mrmcgreg

Reputation: 2816

Consider pascal 1 0. If you're using zero-based indexing for the table then this should be equal to 1. But:

pascal 1 0 = pascal 0 -1 + pascal 0 0 = 2

You should put some guards to deal with negative indices and indices where j is greater than i.

Upvotes: 2

Related Questions