flan/test/programs/higher-order.flan
Joseph Ferano a0f37e72a2 The ! suffix retires: a mutator is named for what it does, not marked
The !-means-mutates convention distinguished nothing — there is no
immutable counterpart to contrast with — so every mutating name drops
the mark: sort, sort-by, sort-bytes, swap, reverse, append, append-i64,
append-f64, encode-rune, split-next, map-remove, map-next, and the test
helpers beside them. Two could not simply shed it: map! is map-in-place,
because map is the into transform's word and means the non-mutating
thing; put! is put-at, because put is the Map builtin. The ?-means-asks
convention stays. Dated records keep the old spellings; watch.clj's
reset-spies! and the other Clojure names are not ours to rename.
2026-09-19 05:21:02 +07:00

51 lines
2.0 KiB
Plaintext

;; The prelude's function-taking family: map-in-place, filter, reduce and a comparator
;; sort. These were the four the second tier could not write, and they arrived
;; the day function values did — so what this checks is that they are ordinary
;; prelude functions, called the ordinary way, with the function passed by
;; name or written inline.
(defn triple [x i32] i32 (* x 3))
(defn odd? [x i32] bool (= (% x 2) 1))
(defn adds [a i32 b i32] i32 (+ a b))
(defn longer-first [a i32 b i32] bool (> a b))
(defn halve [x f32] f32 (/ x 2.0))
(defn big? [x f32] bool (> x 1.0))
(defn main [] i32
;; map-in-place writes back into the slice it was handed.
(let [xs [1 2 3 4]
s (slice xs 0 4)]
(map-in-place s triple)
(print (at s 0)) (print " ") (print (at s 3)) (println "")
;; reduce, with the accumulator first in the step. The prelude's own
;; sum-i32 is this with the + written in.
(print (reduce s 0 adds)) (println "")
;; ... and an fn literal, whose parameter types come from the parameter.
(print (reduce s 1 (fn [a b] (* a b)))) (println "")
;; filter allocates and the caller frees.
(let [v (filter s odd?)]
(print (len v)) (print " ") (print (at v 0)) (println "")
(free v))
;; A comparator sort, both directions off the same slice.
(sort-by s longer-first)
(print (at s 0)) (print " ") (print (at s 3)) (println "")
(sort-by s (fn [a b] (< a b)))
(print (at s 0)) (print " ") (print (at s 3)) (println ""))
;; The f32 half of the family, which is the same code at the other element
;; type — the copy that generics would remove.
(let [ys [(f32 4.0) (f32 1.0) (f32 8.0) (f32 2.0)]
t (slice ys 0 4)]
(map-in-place t halve)
(print (at t 0)) (print " ") (print (at t 2)) (println "")
(print (reduce t 0.0 (fn [a b] (+ a b)))) (println "")
(let [w (filter t big?)]
(print (len w)) (println "")
(free w))
(sort-by t (fn [a b] (> a b)))
(print (at t 0)) (print " ") (print (at t 3)) (println ""))
0)