Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Represent sequence of tetrahedral numbers in Haskell

Tags:

list

haskell

I've been wanting to learn some Haskell for a while now, and I know it and similar languages have really good support for various kinds of infinite lists. So, how could I represent the sequence of tetrahedral numbers in Haskell, preferably with an explanation of what's going on?

0   0   0
1   1   1
2   3   4
3   6   10
4   10  20
5   15  35
6   21  56
7   28  84
8   36  120

In case it's not clear what's going on there, the second column is a running total of the first column, and the third column is a running total of the second column. I'd prefer that the Haskell code retain something of the "running total" approach, since that's the concept I was wondering how to express.

like image 621
We Are All Monica Avatar asked Sep 29 '10 03:09

We Are All Monica


1 Answers

You're correct, Haskell is really nice for doing things like this:

first_col = [0..]
second_col = scanl1 (+) first_col
third_col = scanl1 (+) second_col
  • first_col is an infinite list of integers, starting at 0
  • scanl (+) calculates a lazy running sum: Prelude docs

We can verify that the above code is doing the right thing:

Prelude> take 10 first_col 
[0,1,2,3,4,5,6,7,8,9]
Prelude> take 10 second_col 
[0,1,3,6,10,15,21,28,36,45]
Prelude> take 10 third_col 
[0,1,4,10,20,35,56,84,120,165]
like image 181
perimosocordiae Avatar answered Nov 15 '22 01:11

perimosocordiae