From e5d01a4e1918cc558f99f06210b0de410cac3148 Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Mon, 10 Feb 2020 18:13:04 -0800 Subject: [PATCH] Add the primes program from compiler series --- code/compiler/09/examples/primes.txt | 129 +++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 code/compiler/09/examples/primes.txt diff --git a/code/compiler/09/examples/primes.txt b/code/compiler/09/examples/primes.txt new file mode 100644 index 0000000..9394668 --- /dev/null +++ b/code/compiler/09/examples/primes.txt @@ -0,0 +1,129 @@ +data List = { Nil, Cons Nat List } +data Bool = { True, False } +data Nat = { O, S Nat } + +defn ifN c t e = { + case c of { + True -> { t } + False -> { e } + } +} + +defn ifL c t e = { + case c of { + True -> { t } + False -> { e } + } +} + +defn toInt n = { + case n of { + O -> { 0 } + S np -> { 1 + toInt np } + } +} + +defn lte n m = { + case m of { + O -> { + case n of { + O -> { True } + S np -> { False } + } + } + S mp -> { + case n of { + O -> { True } + S np -> { lte np mp } + } + } + } +} + +defn minus n m = { + case m of { + O -> { n } + S mp -> { + case n of { + O -> { O } + S np -> { + minus np mp + } + } + } + } +} + +defn mod n m = { + ifN (lte m n) (mod (minus n m) m) n +} + +defn notDivisibleBy n m = { + case (mod m n) of { + O -> { False } + S mp -> { True } + } +} + +defn filter f l = { + case l of { + Nil -> { Nil } + Cons x xs -> { ifL (f x) (Cons x (filter f xs)) (filter f xs) } + } +} + +defn map f l = { + case l of { + Nil -> { Nil } + Cons x xs -> { Cons (f x) (map f xs) } + } +} + +defn nats = { + Cons (S (S O)) (map S nats) +} + +defn primesRec l = { + case l of { + Nil -> { Nil } + Cons p xs -> { Cons p (primesRec (filter (notDivisibleBy p) xs)) } + } +} + +defn primes = { + primesRec nats +} + +defn take n l = { + case l of { + Nil -> { Nil } + Cons x xs -> { + case n of { + O -> { Nil } + S np -> { Cons x (take np xs) } + } + } + } +} + +defn head l = { + case l of { + Nil -> { O } + Cons x xs -> { x } + } +} + +defn reverseAcc a l = { + case l of { + Nil -> { a } + Cons x xs -> { reverseAcc (Cons x a) xs } + } +} + +defn reverse l = { + reverseAcc Nil l +} + +defn main = { + toInt (head (reverse (take ((S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S O))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) primes))) +}