Skip to content

Instantly share code, notes, and snippets.

@tiensonqin
Created February 11, 2014 02:23
Show Gist options
  • Save tiensonqin/8928192 to your computer and use it in GitHub Desktop.
Save tiensonqin/8928192 to your computer and use it in GitHub Desktop.
-module(pascal).
-export([triangle/1]).
triangle(Rows) ->
triangle([[0,1,0]],1,Rows).
triangle(List, Count, Rows) when Count >= Rows -> lists:reverse(List);
triangle(List, Count, Rows) ->
[Previous | _] = List,
triangle([add_row(Previous) | List], Count+1, Rows).
add_row(Initial) ->
add_row(Initial, 0, []). % last initialize to zero
add_row([], 0, Final) ->
[0 | Final];
add_row([H | T], Last, New) ->
add_row(T, H, [Last + H | New]).
%% 1
%% 1 1
%% 1 2 1
%% 1 3 3 1
%% Endpoint: no element left in the old list
%% Rule: new element = current + next
%% Trace:
%% H T Last New T H [Last + H | New]
%% 0 [1,0] 0 [] => [1,0], 0, [0]
%% 1 [0] 0 [0] => [0], 1, [1,0]
%% 0 [] 1 [1,0] => [], 0, [1,1,0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment