Carp/examples/generic_structs.carp
2019-10-31 06:23:23 -03:00

46 lines
1.5 KiB
Plaintext

(Debug.sanitize-addresses)
(Project.no-echo)
(use Array)
(deftype (Trivial t) [x t])
(defn construct-from-ref [r]
(Trivial.init @r))
;; Simplified dictionary:
(deftype (Entry a b) [key a value b])
(deftype (Bucket a b) [entries (Array (Entry a b))])
(defn lookup [bucket lookup-key]
(let-do [pairs (Bucket.entries bucket)
result (zero)]
(for [i 0 (length pairs)]
(let [pair (unsafe-nth pairs i)]
(when (= (Entry.key pair) &lookup-key)
(set! result @(Entry.value pair)))))
result))
(defn try-dictionary []
(let-do [start (Bucket.init [(Entry.init @"hello" 12345)
(Entry.init @"goodbye" 666)])
other (Bucket.init [(Entry.init true @"yo")
(Entry.init false @"no")])]
(IO.println &(str &start))
(IO.println &(str (lookup &start @"hello")))
(IO.println &(str &(lookup &other true)))
))
(defn main []
(do
(println* &(Array.repeat-indexed 5 Trivial.init))
(println* &(Array.copy-map &construct-from-ref &(Array.repeat-indexed 5 Trivial.init)))
(IO.println (ref (str &(Pair.init (Pair.init [(Pair.init 1.0f \q)] 20) (Pair.init true false)))))
(IO.println &(str &(Pair.init 10 @"hello")))
(IO.println &(str &(Pair.init true 3.2)))
(IO.println &(str &(Pair.init [1 2 3] [true false true false])))
(IO.println &(str &(Pair.update-a (Pair.init 100 100) &Int.inc)))
(IO.println &(str &(Pair.set-b (Pair.init 100 100) 200)))
(IO.println &(str @(Pair.a &(Pair.init 100 100))))
(try-dictionary)
))