From 75861bf1c74df40bd72d4ae17d4b25c68457dd1a Mon Sep 17 00:00:00 2001 From: Pekka Laiho Date: Sat, 6 Jun 2020 16:25:49 +0700 Subject: [PATCH] factorial functions --- mad/fact.mad | 7 +++++++ mad/fib.mad | 8 ++++---- 2 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 mad/fact.mad diff --git a/mad/fact.mad b/mad/fact.mad new file mode 100644 index 0000000..9ecaa3e --- /dev/null +++ b/mad/fact.mad @@ -0,0 +1,7 @@ +;; Functions to calculate factorial + +;; Recursive version +(def recFact (fn (n) (if (< n 2) 1 (* n (recFact (- n 1)))))) + +;; Apply version +(def applyFact (fn (n) (if (< n 2) 1 (apply * (range 1 (+ n 1)))))) diff --git a/mad/fib.mad b/mad/fib.mad index 61eb631..2883128 100644 --- a/mad/fib.mad +++ b/mad/fib.mad @@ -1,11 +1,11 @@ -; Functions to calculate Fibonacci numbers +;; Functions to calculate Fibonacci numbers -; Slow recursive version +;; Slow recursive version (def slowFib (fn (n) (if (< n 2) n (+ (slowFib (- n 1)) (slowFib (- n 2)))))) -; Return the sum of the last 2 numbers in a sequence +;; Return the sum of the last 2 numbers in a sequence (def sumOfLast (fn (l) (+ (last l) (get l (- (len l) 2))))) -; Faster version, return vector of n numbers +;; Faster version, return vector of n numbers (def fibListRec (fn (n l) (if (< (len l) n) (fibListRec n (push l (sumOfLast l))) l))) (def fibList (fn (n) (fibListRec n [0 1])))