Add support for multiple statements in sequences
This commit is contained in:
parent
584a40d9c0
commit
a7f6d1d3f7
@ -26,6 +26,7 @@ the sequence:
|
||||
.. code-block:: hy
|
||||
|
||||
(seq [n]
|
||||
"sequence of 5 integers"
|
||||
(cond [(< n 5) n]
|
||||
[true (end-sequence)]))
|
||||
|
||||
@ -40,6 +41,7 @@ is defined as:
|
||||
.. code-block:: hy
|
||||
|
||||
(defseq fibonacci [n]
|
||||
"infinite sequence of fibonacci numbers"
|
||||
(cond [(= n 0) 0]
|
||||
[(= n 1) 1]
|
||||
[true (+ (get fibonacci (- n 1))
|
||||
|
@ -67,11 +67,11 @@
|
||||
"string representation of this sequence"
|
||||
(.--str-- self))])
|
||||
|
||||
(defmacro seq [param seq-code]
|
||||
`(Sequence (fn ~param ~seq-code)))
|
||||
(defmacro seq [param &rest seq-code]
|
||||
`(Sequence (fn ~param (do ~@seq-code))))
|
||||
|
||||
(defmacro defseq [seq-name param seq-code]
|
||||
`(def ~seq-name (seq ~param ~seq-code)))
|
||||
(defmacro defseq [seq-name param &rest seq-code]
|
||||
`(def ~seq-name (seq ~param (do ~@seq-code))))
|
||||
|
||||
(defn end-sequence []
|
||||
"raise IndexError exception to signal end of sequence"
|
||||
|
@ -85,3 +85,27 @@
|
||||
(assert (= (list (take 9 fibonacci))
|
||||
[0 1 1 2 3 5 8 13 21])
|
||||
"taking 8 elements of fibonacci didn't match"))
|
||||
|
||||
(defn test-nested-functions []
|
||||
"NATIVE: test that defining nested functions is possible"
|
||||
(defseq primes [n]
|
||||
"infinite sequence of prime numbers"
|
||||
(defn divisible? [n prevs]
|
||||
"is n divisible by any item in prevs?"
|
||||
(any (map (fn [x]
|
||||
(not (% n x)))
|
||||
prevs)))
|
||||
(defn previous-primes [n]
|
||||
"previous prime numbers"
|
||||
(take (dec n) primes))
|
||||
(defn next-possible-prime [n]
|
||||
"next possible prime after nth prime"
|
||||
(inc (get primes (dec n))))
|
||||
(cond [(= n 0) 2]
|
||||
[true (do (setv guess (next-possible-prime n))
|
||||
(while (divisible? guess (previous-primes n))
|
||||
(setv guess (inc guess)))
|
||||
guess)]))
|
||||
(assert (= (list (take 10 primes))
|
||||
[2 3 5 7 11 13 17 19 23 29])
|
||||
"prime sequence didn't match"))
|
||||
|
Loading…
x
Reference in New Issue
Block a user