Update maxtriangle example, extend map function, and

add extremes functions (max, min, order-max, order-min, extreme)
This commit is contained in:
Calvin Rose 2018-04-01 15:08:51 -04:00
parent 027b2a81c2
commit 1110267c9d
2 changed files with 42 additions and 31 deletions

View File

@ -1,36 +1,18 @@
# Find the maximum path from the top (root)
# of the triangle to the leaves of the triangle.
(defn vmap2 [f m1 m2]
(def len (length m1))
(def arr @[])
(for [i 0 len] (array-push arr (f (get m1 i) (get m2 i))))
arr)
(defn reduce [s f c]
(var res s)
(for [i 0 (length c)]
(:= res (f res (get c i))))
res)
(defn max1 [l r] (if (< l r) r l))
(defn myfold [xs ys]
(def xs1 (tuple-prepend xs 0))
(def xs2 (tuple-append xs 0))
(def m1 (vmap2 + xs1 ys))
(def m2 (vmap2 + xs2 ys))
(vmap2 max1 m1 m2))
(defn max [a]
(var m (get a 0))
(for [i 0 (length a)]
(if (< m (get a i))
(:= m (get a i))))
m)
(def m1 (map + xs1 ys))
(def m2 (map + xs2 ys))
(map max m1 m2))
(defn maxpath [t]
(max (reduce () myfold t)))
(extreme > (reduce myfold () t)))
# Test it
# Maximum path is 3 -> 10 -> 3 -> 9 for a total of 25
(def triangle @[
@[3]

View File

@ -304,6 +304,23 @@ evaluates to true."
[f]
(fn [x] (not (f x))))
(defn extreme
"Returns the most extreme value in args based on the orderer order.
Returns nil if args is empty."
[order args]
(def len (length args))
(when (pos? len)
(var ret (get args 0))
(for [i 0 len]
(def v (get args i))
(if (order v ret) (:= ret v)))
ret))
(defn max [& args] (extreme > args))
(defn min [& args] (extreme < args))
(defn max-order [& args] (extreme order> args))
(defn min-order [& args] (extreme order< args))
###
###
### Indexed Combinators
@ -366,13 +383,25 @@ an indexed type (array, tuple) with a function to produce a value."
(defn map
"Map a function over every element in an array or tuple and return
the same type as the input sequence."
[f ind t]
[f & inds]
(def res @[])
(for [i 0 (length ind)]
(array-push res (f (get ind i))))
(if (= :tuple (type (or t ind)))
(apply1 tuple res)
res))
(def ninds (length inds))
(if (= 0 ninds) (error "expected at least 1 indexed collection."))
(var limit (length (get inds 0)))
(for [i 0 ninds]
(def l (length (get inds i)))
(if (< l limit) (:= limit l)))
(def [i1 i2 i3 i4] inds)
(switch ninds
1 (for [i 0 limit] (array-push res (f (get i1 i))))
2 (for [i 0 limit] (array-push res (f (get i1 i) (get i2 i))))
3 (for [i 0 limit] (array-push res (f (get i1 i) (get i2 i) (get i3 i))))
4 (for [i 0 limit] (array-push res (f (get i1 i) (get i2 i) (get i3 i) (get i4 i))))
(for [i 0 limit]
(def args @[])
(for [j 0 ninds] (array-push args (get (get inds j) i)))
(array-push res (apply1 f args))))
res)
(defn mapcat
"Map a function over every element in an array or tuple and