Skip to content

Commit

Permalink
Add while loop, fix three.gel
Browse files Browse the repository at this point in the history
  • Loading branch information
surrsurus committed Nov 2, 2017
1 parent 5bba98a commit bea370b
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 11 deletions.
2 changes: 1 addition & 1 deletion euler/one.gel
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
(begin
;; Project euler question 1 answer
;; 233168
(return (sum (filter (\ (n) (or (= (% n 5) 0) (= (% n 3) 0))) (range 1000))))
(display (sum (filter (\ (n) (or (= (% n 5) 0) (= (% n 3) 0))) (range 1000))))
)

46 changes: 37 additions & 9 deletions euler/three.gel
Original file line number Diff line number Diff line change
@@ -1,16 +1,44 @@
(begin
;; Project Euler question 3 answer
;; 3 different procedures for computation

(def (primefac i f)
(if (< i f)
(return '())
(if (= (% i f) 0)
(return (append (list f) (primefac (/ i f) 2)))
(return (primefac i (+ f 1)))
)
;; Recursive method
;; Breaks python's recursion depth
;; i should be 2 on start
(def (primefac-recur-break n i)
(if (= (% n i) 0)
(return (append (list i) (primefac-recur (/ n i) 2)))
(return (primefac-recur n (+ i 1)))
)
)

;; Another recursive method that doesn't break python
;; i should be 2 on start
(def (primefac-recur n i) (begin
(if (<= (* i i) n)
(if (> (% n i) 0)
(primefac-recur n (+ i 1))
(primefac-recur (// n i) i)
)
(return n)
)
))

;; While loop method
;; The least ideal out of all of them
(def (primefac n) (begin
(def i 2)
(while (<= (* i i) n)
(if (> (% n i) 0)
(set! i (+ i 1))
(set! n (// n i))
)
)
(return n)
))

;; Will cause recursion error.
(return (max (primefac 600851475143 2)))
;; 6857
;; (display (primefac 600851475143))
(display (primefac-recur 600851475143 2))

)
9 changes: 9 additions & 0 deletions gazelle/parseval.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,15 @@ def eval(expr, env=global_env):
elif procedure == Symbols['include']:
(_, file) = expr
return eval(parse(Atomizer(open(file))))

# (while cond body)
elif procedure == Symbols['while']:

(_, cond, body) = expr
while eval(cond, env):
eval(body, env)

return None

# (proc expr*)
else:
Expand Down
3 changes: 2 additions & 1 deletion gazelle/sym.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ def Sym(s, symbol_table={}):
'return': Sym('return'),
'set!': Sym('set!'),
'unquote': Sym('unquote'),
'unquotesplicing': Sym('unquotesplicing')
'unquotesplicing': Sym('unquotesplicing'),
'while': Sym('while'),
}

# Quotes such as these must be expanded into
Expand Down

0 comments on commit bea370b

Please sign in to comment.