A peer-to-peer stack for code collaboration
{:module 'prelude/basic
:doc "Basic function used for checking equality, determining the type of a value, etc."
:exports '[or some empty-seq? length maybe->>= maybe-foldlM elem? head tail read read-many <=]}
;; or
(def head
"Backwards compatible alias for `first`."
first)
(def tail
"Backwards compatible alias for `rest`."
rest)
(def or
"Returns `x` if `x` is not `#f`, otherwise returns `y`"
(fn [x y]
(if x x y)))
(:test "or"
[ (or #t #t) ==> #t ]
[ (or #t #f) ==> #t ]
[ (or #f #t) ==> #t ]
[ (or #f #f) ==> #f ]
)
;; some
(def some
"Checks that there is a least one truthy value in a list."
(fn [xs] (foldr or #f xs)))
(:test "some"
[ (some '()) ==> #f ]
[ (some '(#t)) ==> #t ]
[ (some '(#f)) ==> #f ]
[ (some '(#f #f #f)) ==> #f ]
[ (some '(#t #t #t #t)) ==> #t ]
[ (some '(#t #t #f #t)) ==> #t ]
)
(def empty-seq?
"Returns true if `xs` is an empty sequence (either list or vector)."
(fn [xs]
(or (eq? xs (list))
(eq? xs []))))
;; TODO move to file for primitive tests
(:test "length"
[ (length (list)) ==> 0]
[ (length (list 2)) ==> 1]
[ (length []) ==> 0]
[ (length [1 2]) ==> 2]
[ (length "") ==> 0]
[ (length "abc") ==> 3]
)
(def maybe->>=
"Monadic bind for the maybe monad."
(fn [v f]
(if (vector? v)
(if (eq? (length v) 2)
(if (eq? (nth 0 v) :just)
(f (nth 1 v))
:nothing)
:nothing)
:nothing)))
(def-rec maybe-foldlM
"Monadic fold over the elements of a sequence `xs`, associating to the left (i.e. from
left to right) in the maybe monad."
(fn [f i xs]
(if (empty-seq? xs)
[:just i]
(maybe->>= (f i (nth 0 xs))
(fn [b] (maybe-foldlM f b (drop 1 xs)))))))
;; elem?
(def elem?
"Returns true if `x` is an element of the sequence `xs`"
(fn [x xs]
(some (map (fn [c] (eq? c x)) xs))))
(:test "elem?"
[ (elem? "f" (list "f" "g" "h")) ==> #t]
[ (elem? "h" ["f" "g" "h"]) ==> #t]
[ (elem? "a" (list "f" "g" "h")) ==> #f])
(def read
"Reads a radicle value from a string."
(fn [s]
(read-annotated "[read]" s)))
(:test "read"
[ (read "[:a 42 \"foo\" {:key (1 2 3)}]") ==> [:a 42 "foo" {:key (1 2 3)}] ])
(def read-many
"Reads many radicle values from a string."
(fn [s]
(read-many-annotated "[read-many]" s)))
(:test "read-many"
[ (read-many "([:one] {:two 3}) (four \"five\" 6)") ==> [([:one] {:two 3}) (four "five" 6)]])
(def <=
"Test if `x` is less than or equal to `y`."
(fn [x y] (or (eq? x y) (< x y))))