Last active
April 21, 2017 21:21
-
-
Save andreiglingeanu/85782a307fa4c79d826d8fbc94dcff72 to your computer and use it in GitHub Desktop.
Compute Nth Pascal row with Mozart language: https://en.wikipedia.org/wiki/Pascal%27s_triangle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 1: 1 | |
% 2: 1 1 | |
% 3: 2 1 1 | |
% 4: 1 3 3 1 | |
% N: | |
declare Pascal AddList ShiftLeft ShiftRight | |
fun {Pascal N} | |
if N==1 then [1] | |
else | |
{AddList {ShiftLeft {Pascal N - 1}} | |
{ShiftRight {Pascal N - 1}}} | |
end | |
end | |
fun lazy {PascalList Row} | |
Row | {PascalList | |
{AddList {ShiftLeft Row} | |
{ShiftRight Row}}} | |
end | |
fun {PascalList2 N Row} | |
if N==1 then [Row] | |
else | |
Row | {PascalList2 N - 1 | |
{AddList {ShiftLeft Row} | |
{ShiftRight Row}}} | |
end | |
end | |
fun {FastPascal N} | |
if N==1 then [1] | |
else L in | |
L={FastPascal N-1} | |
{AddList {ShiftLeft L} {ShiftRight L}} | |
end | |
end | |
fun {ShiftLeft L} | |
case L of H | T then | |
H | {ShiftLeft T} | |
else | |
[0] | |
end | |
end | |
fun {ShiftRight L} | |
0 | L | |
end | |
fun {AddList L1 L2} | |
case L1 of H1 | T1 then | |
case L2 of H2 | T2 then | |
H1 + H2 | {AddList T1 T2} | |
else | |
nil | |
end | |
else | |
nil | |
end | |
end | |
{Show {FastPascal 30}} | |
% Show 3 rows after the row [1 2 1] | |
{Show {PascalList2 3 [1 2 1]}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment