A peer-to-peer stack for code collaboration
Pattern matching (#230)
James Haydond47d90e82cc9
diff --git a/docs/source/reference.rst b/docs/source/reference.rstindex 5b26faa..8fd4f55 100644--- a/docs/source/reference.rst+++ b/docs/source/reference.rst@@ -95,6 +95,11 @@ Checks if the argument is a number.Checks if the argument is a keyword.+``vector?``+~~~~~~~~~~~++Checks if the argument is a vector.+``list?``~~~~~~~~~@@ -175,6 +180,12 @@ Multiplies two numbers together.Substracts one number from another.+``/``+~~~~~++Divides one number by another. Throws an exception if the second+argument is 0.+``<``~~~~~@@ -285,6 +296,11 @@ SequencesFunctions for manipulating boths lists and vectors.+``empty-seq?``+~~~~~~~~~~~~~~++Returns true if the input is an empty sequence (either list or vector).+``nth``~~~~~~~@@ -342,6 +358,13 @@ is empty, in which case an exception is thrown.Given a sequence ``xs`` and a function ``f``, returns a sequence withthe same elements ``x`` of ``xs`` but sorted according to ``(f x)``.+``zip``+~~~~~~~++Takes two sequences and returns a sequence of corresponding pairs. In+one sequence is shorter than the other, the excess elements of the+longer sequence are discarded.+Dicts-----@@ -351,7 +374,8 @@ Functions for manipulating dicts.~~~~~~~~Given an even number of arguments, creates a dict where the ``2i``-th-argument is the key for the ``2i+1``\ th argument.+argument is the key for the ``2i+1``\ th argument. If one of the even+indexed arguments is not hashable then an exception is thrown.``lookup``~~~~~~~~~~@@ -366,7 +390,7 @@ thrown.Given ``k``, ``v`` and a dict ``d``, returns a dict with the sameassociations as ``d`` but with ``k`` associated to ``d``. If ``d`` isn't-a dict then an exception is thrown.+a dict or if ``k`` isn't hashable then an exception is thrown.``delete``~~~~~~~~~~@@ -413,6 +437,14 @@ associated to that key.Delete several keys from a dict.+``exclusive-dict-merge``+~~~~~~~~~~~~~~~~~~~~~~~~++Merges two dicts while checking for key conflicts. Returns+``{:merge m :conflicts c}`` where ``m`` is the merged dict for all+non-conflicting keys and ``c`` is a dict with all the conflicting keys,+mapping to pairs of values, one from each input dict.+Sets----@@ -466,6 +498,57 @@ structure ``s`` may be a list, vector or dict. If it is a list or avector, it checks if ``v`` is one of the items. If ``s`` is a dict, itchecks if ``v`` is one of the keys.+Patterns+--------++Pattern matching is first-class in radicle so new patterns can easily be+defined. These are the most essential.++``match-pat``+~~~~~~~~~~~~~++The pattern matching dispatch function. This function defines how+patterns are treated in ``match`` expressions. Atoms are treated as+bindings. Numbers, keywords and strings are constant patterns. Dicts of+patterns match dicts whose values at those keys match those patterns.+Vectors of patterns match vectors of the same length, pairing the+patterns and elements by index.++``_``+~~~~~++The wildcard pattern.++``/?``+~~~~~~++Predicate pattern. Takes a predicate function as argument. Values match+against this pattern if the predicate returns a truthy value.++``/nil``+~~~~~~~~++Empty-list pattern.++``/cons``+~~~~~~~~~++A pattern for lists with a head and a tail.++``/as``+~~~~~~~++As pattern. Takes a variable and a sub-pattern. If the subpattern+matches then the whole pattern matches and furthermore the variable is+bound to the matched value.++``non-linear-merge``+~~~~~~~~~~~~~~~~~~~~++The bindings merge strategy for non-linear patterns. Use this function+to merge bindings returned by sub-patterns if you want your pattern to+be non-linear.+Refs----@@ -654,6 +737,28 @@ Exit the interpreter immediately.Returns a timestamp for the current Coordinated Universal Time (UTC),right now, formatted according to ISO 8601.+Maybe+-----++Optionality is represented using ``[:Just x]`` for when the value+exists, and ``:Nothing`` when it doesn't.++``/Just``+~~~~~~~~~++Pattern which matches ``[:Just x]``.++``maybe->>=``+~~~~~~~~~~~~~++Monadic bind for the maybe monad.++``maybe-foldlM``+~~~~~~~~~~~~~~~~++Monadic fold over the elements of a seq, associating to the left (i.e.+from left to right) in the maybe monad.+Lenses------@@ -837,6 +942,11 @@ functions before sending these to a remote chain.Return an empty chain dictionary with the given url.+``@var``+~~~~~~~~++A lens for variables in states of chains.+``eval-in-chain``~~~~~~~~~~~~~~~~~diff --git a/exe/ReferenceDoc.hs b/exe/ReferenceDoc.hsindex 46fd96e..1fb81f7 100644--- a/exe/ReferenceDoc.hs+++ b/exe/ReferenceDoc.hs@@ -51,6 +51,8 @@ main = do, sec "Dicts" dicts $ typ "dicts", sec "Sets" sets $ typ "sets", sec "Structures" structs $ typ "lists, vectors and dicts"+ , sec "Patterns" patterns+ "Pattern matching is first-class in radicle so new patterns can easily be defined. These are the most essential.", sec "Refs" refs "Functions for creating, querying and modifying refs.", sec "Evaluation functions" evalFns "Utilities for creating and extending evaluation functions.", sec "Documentation and testing" docs@@ -58,6 +60,8 @@ main = do, sec "Environment functions" envStuff "Utilities for modifying the current environment.", sec "Input/Output" io"Effectful functions. These functions are not available in 'pure' chains, but are available in the local REPL."+ , sec "Maybe" maybe'+ "Optionality is represented using `[:Just x]` for when the value exists, and `:Nothing` when it doesn't.", sec "Lenses" lens"Functional references into radicle values.", sec "Validation" validation@@ -74,22 +78,23 @@ main = dobasics =[ "eq?", "not", "and", "or", "all", "some", "show", "string-append", "string-length"- , "apply", "type", "atom?", "boolean?", "string?", "number?", "keyword?", "list?"+ , "apply", "type", "atom?", "boolean?", "string?", "number?", "keyword?", "vector?", "list?", "dict?", "read", "read-many", "throw", "Y", "Y2", "to-json", "uuid?", "make-counter", "public-key?" ]maths = ["+", "*", "-", "/", "<", ">", "integral?"]evalFns = ["base-eval", "eval", "updatable-eval"]envStuff = ["pure-env", "get-current-env", "set-current-env", "set-env!"]- seqs = ["nth", "foldl", "foldr", "map", "seq", "take", "drop", "sort-by"]+ seqs = ["empty-seq?", "nth", "foldl", "foldr", "map", "seq", "take", "drop", "sort-by", "zip"]lists =[ "list", "nil", "head", "tail", "empty?", "cons", "reverse", "length", "concat", "filter", "range", "list-with-head" ]vecs = ["<>", "add-left", "add-right"]dicts =["dict", "lookup", "insert", "delete", "dict-from-list", "keys", "values", "rekey"- , "map-values", "modify-map", "delete-many"]+ , "map-values", "modify-map", "delete-many", "exclusive-dict-merge"]sets = ["set/empty", "set/insert", "set/delete", "set/member?", "set/delete", "set/from-seq", "set/to-vec"]structs = ["member?"]+ patterns = ["match-pat", "_", "/?", "/nil", "/cons", "/as", "non-linear-merge"]refs = ["ref", "read-ref", "write-ref", "modify-ref"]docs = ["help", "doc", "doc!", "apropos!", "document", "is-test-env"]io =@@ -97,6 +102,7 @@ main = do, "load!", "read-file!", "read-code!", "send-code!", "send-prelude!", "subscribe-to!", "uuid!", "read-line!", "exit!", "now!"]+ maybe' = ["/Just", "maybe->>=", "maybe-foldlM"]lens = ["@", "@nth", "make-lens", "view", "view-ref", "set", "set-ref", "over", "over-ref", "id-lens", "..", "..."]validation =[ "validator/=", "validator/member", "validator/type", "validator/pred", "validator/every"@@ -117,7 +123,8 @@ main = doallFns =basics ++ maths ++ evalFns ++ envStuff ++ seqs ++ lists ++ vecs- ++ dicts ++ sets ++ structs ++ refs ++ docs ++ io ++ lens ++ validation ++ crypto ++ chainTools+ ++ dicts ++ sets ++ structs ++ patterns ++ refs ++ docs ++ io ++ maybe' ++ lens ++ validation ++ crypto ++ chainTools+ -- ++ issueChain++ doNotInclude-- Function symbol followed by a hard line break, followed by it's doc.diff --git a/rad/prelude.rad b/rad/prelude.radindex ab952f8..36fb0a1 100644--- a/rad/prelude.rad+++ b/rad/prelude.rad@@ -1,4 +1,6 @@(load! "rad/prelude/test.rad")+(load! "rad/prelude/basic.rad")+(load! "rad/prelude/patterns.rad")(load! "rad/prelude/io.rad")(load! "rad/prelude/bool.rad")(load! "rad/prelude/exception.rad")@@ -16,6 +18,8 @@(def pure-prelude-files(list"rad/prelude/test.rad" ;; pure unless test env+ "rad/prelude/basic.rad"+ "rad/prelude/patterns.rad""rad/prelude/pure-should-be.rad""rad/prelude/recursion.rad""rad/prelude/bool.rad"diff --git a/rad/prelude/basic.rad b/rad/prelude/basic.radnew file mode 100644index 0000000..c3841c1--- /dev/null+++ b/rad/prelude/basic.rad@@ -0,0 +1,52 @@+;; or++(def or+ (fn [x y]+ (if x x y)))++(document 'or+ '(("arg1" any) ("arg2" any))+ "Returns 'arg1' if 'arg1' is not #f, otherwise returns 'arg2'")++(: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 the input is an empty sequence (either list or vector)."+ (fn [xs]+ (or (eq? xs (list))+ (eq? xs []))))++;; length++(def length+ (fn [xs]+ (foldr (fn [x acc] (+ acc 1)) 0 xs)))++(document 'length+ '(("list" list))+ "Returns the length of 'list'.")++(:test "length"+ [ (length (list)) ==> 0]+ [ (length (list 2)) ==> 1]+)diff --git a/rad/prelude/bool.rad b/rad/prelude/bool.radindex 86df94f..4f2e48e 100644--- a/rad/prelude/bool.rad+++ b/rad/prelude/bool.rad@@ -26,23 +26,6 @@[ (and #f #f) ==> #f ])-;; or--(def or- (fn [x y]- (if x x y)))--(document 'or- '(("arg1" any) ("arg2" any))- "Returns 'arg1' if 'arg1' is not #f, otherwise returns 'arg2'")--(:test "or"- [ (or #t #t) ==> #t ]- [ (or #t #f) ==> #t ]- [ (or #f #t) ==> #t ]- [ (or #f #f) ==> #f ]-)-;; all(def all@@ -55,19 +38,4 @@[ (all '(#f)) ==> #f ][ (all '(#t #t #t #t)) ==> #t ][ (all '(#t #t #f #t)) ==> #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 ]-)+)\ No newline at end of filediff --git a/rad/prelude/list.rad b/rad/prelude/list.radindex d374f0e..5d5915d 100644--- a/rad/prelude/list.rad+++ b/rad/prelude/list.rad@@ -18,21 +18,6 @@[ (empty? []) ==> #t ])-;; length--(def length- (fn [xs]- (foldr (fn [x acc] (+ acc 1)) 0 xs)))--(document 'length- '(("list" list))- "Returns the length of 'list'.")--(:test "length"- [ (length nil) ==> 0]- [ (length (list 2)) ==> 1]-)-;; reverse(def reverse (fn [ls]diff --git a/rad/prelude/patterns.rad b/rad/prelude/patterns.radnew file mode 100644index 0000000..093166a--- /dev/null+++ b/rad/prelude/patterns.rad@@ -0,0 +1,229 @@+;; Because pattern matching uses the Maybe-monad, it's helpful to define some+;; essential Maybe-monad function now.++(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 seq, 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)))))))++(def exclusive-dict-merge+ "Merges two dicts while checking for key conflicts. Returns `{:merge+ m :conflicts c}` where `m` is the merged dict for all non-conflicting keys and+ `c` is a dict with all the conflicting keys, mapping to pairs of values, one+ from each input dict."+ (fn [m n]+ (foldr (fn [kv acc]+ (def k (nth 0 kv))+ (def v (nth 1 kv))+ (def merge (lookup :merge acc))+ (if (member? k merge)+ {:merge (delete k merge)+ :conflicts (insert k [(lookup k merge) v] (lookup :conflicts acc))}+ (insert :merge (insert k v merge) acc)))+ {:merge m+ :conflicts {}}+ (seq n))))++(def non-linear-merge+ "The bindings merge strategy for non-linear patterns. Use this function to merge+ bindings returned by sub-patterns if you want your pattern to be non-linear."+ (fn [m n]+ (def excl-merge (exclusive-dict-merge m n))+ (def cs (lookup :conflicts excl-merge))+ (def merge (lookup :merge excl-merge))+ (if (eq? cs {})+ [:Just merge]+ (maybe-foldlM (fn [acc kv]+ (def v (nth 1 kv))+ (def v0 (nth 0 v))+ (if (eq? v0 (nth 1 v))+ [:Just (insert (nth 0 kv) v0 acc)]+ :Nothing))+ merge+ (seq cs)))))+(def _+ "The wildcard pattern."+ (fn [v] [:Just {}]))++(def-rec match-pat+ "The pattern matching dispatch function. This function defines how patterns+ are treated in `match` expressions. Atoms are treated as bindings. Numbers,+ keywords and strings are constant patterns. Dicts of patterns match dicts+ whose values at those keys match those patterns. Vectors of patterns match+ vectors of the same length, pairing the patterns and elements by index."+ (fn [pat v]+ (def /vec+ (fn [pats]+ (fn [v]+ (if (eq? (length v) (length pat))+ (maybe-foldlM+ (fn [acc pair]+ (maybe->>= (match-pat (nth 0 pair) (nth 1 pair))+ (fn [bs] (non-linear-merge acc bs))))+ {}+ (zip pats v))+ :Nothing))))+ (def /dict+ (fn [keys-pat]+ (fn [d]+ (maybe-foldlM+ (fn [acc kv]+ (def k (nth 0 kv))+ (def pat (nth 1 kv))+ (if (member? k d)+ (maybe->>= (match-pat pat (lookup k d))+ (fn [bs] (non-linear-merge acc bs)))+ :Nothing))+ {}+ (seq keys-pat)))))+ (cond+ (atom? pat)+ [:Just {pat v}]+ (some [(number? pat) (keyword? pat) (string? pat)])+ (if (eq? pat v) [:Just {}] :Nothing)+ (dict? pat)+ ((/dict pat) v)+ (vector? pat)+ ((/vec pat) v)+ :else+ (pat v))))++(:test "basic pattern matching"+ [ (match 42 12 :not-42 'x x) ==> 42 ]+ [ (match 42 12 :not-42 42 :yes) ==> :yes ]+ [ (match :fourty-two :not-42 :no :fourty-two :yes) ==> :yes ]+ [ (match "42" "?" :no "42" :yes) ==> :yes ]+ [ (match {:a :a :b :b} {:a 'a :b 'b} [a b]) ==> [:a :b] ]+ [ (match [1 2 3] ['x _ 'y] [x y]) ==> [1 3] ]+ [ (match {:a 1 :b [1 2 3]}+ 42 :no+ {:a _ :b [_ 2 _]} :yes) ==> :yes]+ [ (match [1 2]+ ['x 'x] :no+ ['x 'y] :yes) ==> :yes ]+ [ (match [1 1]+ ['x 'x] :yes+ ['x 'y] :no) ==> :yes])++(def /Just+ "Pattern which matches `[:Just x]`."+ (fn [pat]+ (fn [v]+ (maybe->>= v+ (fn [x] (match-pat pat x))))))++(:test "Just patterns"+ [ (match [:Just 42] (/Just 'x) x _ :no) ==> 42 ]+ [ (match :Nothing (/Just 'x) x _ :yes) ==> :yes ])++(def /cons+ "A pattern for lists with a head and a tail."+ (fn [x-pat xs-pat]+ (fn [v]+ (if (list? v)+ (if (> (length v) 0)+ (maybe->>=+ (match-pat x-pat (head v))+ (fn [b1]+ (maybe->>=+ (match-pat xs-pat (tail v))+ (fn [b2] (non-linear-merge b1 b2)))))+ :Nothing)+ :Nothing))))++(def /nil+ "Empty-list pattern."+ (fn [v]+ (if (eq? v (list))+ [:Just {}]+ :Nothing)))++(:test "List pattern matching"+ [ (match (list) /nil :yes _ :no) ==> :yes ]+ [ (match (list 1 2 3) /nil :no (/cons 'x 'xs) [x xs]) ==> [1 (2 3)]])++(def /?+ "Predicate pattern. Takes a predicate function as argument. Values match against+ this pattern if the predicate returns a truthy value."+ (fn [p]+ (fn [v]+ (if (p v)+ [:Just {}]+ :Nothing))))++(:test "Predicate patterns"+ [ (match (list)+ (/? (fn [l] (< 0 (length l)))) :no+ _ :yes) ==> :yes]+ [ (match (list 1 2)+ (/? (fn [l] (< 0 (length l)))) :yes+ _ :no) ==> :yes])++(def /as+ "As pattern. Takes a variable and a sub-pattern. If the subpattern matches then+ the whole pattern matches and furthermore the variable is bound to the matched+ value."+ (fn [var pat]+ (if (atom? var)+ (fn [v]+ (maybe->>= (match-pat pat v)+ (fn [bs] [:Just (insert var v bs)])))+ (throw 'pattern-error "The first argument of `/as` should be an atom."))))++(:test "As-patterns work"+ [ (match [1 2 3]+ (/as 'xs [_ 7 _]) :no+ (/as 'xs [_ _ 3]) xs) ==> [1 2 3]]+ [ (match [1 2 [3 4]]+ (/as 'xs [_ 7 _]) :no+ [_ _ (/as 'xs [_ _])] xs) ==> [3 4]]+ )++(:test "Non-linear patterns"+ [ (match [1 1 1]+ ['x 'x 'x] x) ==> 1+ ]+ [ (match [1 1 2]+ ['x 'x 'x] x+ _ :no) ==> :no+ ]++ [ (match [1 [2 3] 3]+ [_ [_ 'x] 'x] x) ==> 3+ ]+ [ (match [1 [2 3] 4]+ [_ [_ 'x] 'x] x+ _ :no) ==> :no+ ]++ [ (match [1 (list 3 1) 3]+ [_ (/cons 'x _) 'x] x) ==> 3+ ]+ [ (match [1 (list 2 3) 4]+ [_ (/cons 'x _) 'x] x+ _ :no) ==> :no+ ]++ [ (match {:a 3 :b [3 2]}+ {:a 'x :b ['x _]} x) ==> 3+ ]+ [ (match {:a 3 :b [2 1]}+ {:a 'x :b ['x _]} x+ _ :no) ==> :no+ ]+)diff --git a/src/Radicle.hs b/src/Radicle.hsindex 420c3aa..7d08c83 100644--- a/src/Radicle.hs+++ b/src/Radicle.hs@@ -39,6 +39,7 @@ module Radicle, untag-- *** LangError, LangError(..)+ , PatternMatchError(..), LangErrorData(..), throwErrorHere, Reference(..)diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex 1261749..53347c5 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -42,6 +42,14 @@ data LangError r = LangError [Ann.SrcPos] (LangErrorData r)instance Serialise r => Serialise (LangError r)+data PatternMatchError+ = NoMatch+ | NoValue+ | BadBindings Value+ deriving (Eq, Show, Read, Generic)++instance Serialise PatternMatchError+-- | An error throw during parsing or evaluating expressions in the language.data LangErrorData r =UnknownIdentifier Ident@@ -54,6 +62,7 @@ data LangErrorData r =| OtherError Text| ParseError (Par.ParseError Char Void)| ThrownError Ident r+ | PatternMatchError PatternMatchError| Exitderiving (Eq, Show, Read, Generic, Functor)@@ -100,6 +109,10 @@ errorDataToValue e = case e of)ParseError _ -> makeVal ("parse-error", [])ThrownError label val -> pure (label, val)+ PatternMatchError pe -> case pe of+ NoValue -> makeVal ( "no-value-to-match", [])+ NoMatch -> makeVal ( "non-exhaustive-pattern-matches", [])+ BadBindings p -> makeVal ( "bad-pattern", [("bad-pattern", p)])Exit -> makeVal ("exit", [])wheremakeA = quote . Atom@@ -493,6 +506,7 @@ specialForms = Map.fromList $ first Ident <$>if b == Boolean False then baseEval f else baseEval txs -> throwErrorHere $ WrongNumberOfArgs "if" 3 (length xs)), ( "cond", (cond =<<) . evenArgs "cond" )+ , ( "match", match )]wherecond = \case@@ -503,6 +517,35 @@ specialForms = Map.fromList $ first Ident <$>then baseEval eelse cond ps+ match = \case+ v : cases -> do+ cs <- evenArgs "match" cases+ v' <- baseEval v+ goMatches v' cs+ _ -> throwErrorHere $ PatternMatchError NoValue++ goMatches _ [] = throwErrorHere (PatternMatchError NoMatch)+ goMatches v ((m, body):cases) = do+ patFn <- baseEval m+ matchPat <- lookupAtom (Ident "match-pat")+ res <- callFn matchPat [patFn, v]+ let res_ = fromRad res+ case res_ of+ Right (Just (Dict binds)) -> do+ b <- bindsToEnv m binds+ addBinds b *> baseEval body+ Right Nothing -> goMatches v cases+ _ -> throwErrorHere $ PatternMatchError (BadBindings m)++ bindsToEnv pat m = do+ is <- traverse isBind (Map.toList m)+ pure $ Env (Map.fromList is)+ where+ isBind (Atom x, v) = pure (x, Doc.Docd Nothing v)+ isBind _ = throwErrorHere $ PatternMatchError (BadBindings pat)++ addBinds e = modify (\s -> s { bindingsEnv = e <> bindingsEnv s })+def name doc_ val = doval' <- baseEval valdefineAtom name doc_ val'@@ -589,7 +632,8 @@ instance FromRad Ann.WithPos (Bindings ()) whereclass ToRad t a wheretoRad :: a -> Annotated t ValueFdefault toRad :: (HasEot a, ToRadG t (Eot a)) => a -> Annotated t ValueF- toRad = toRadG+ toRad =+ toRadGinstance CPA t => ToRad t () wheretoRad _ = Vec Emptydiff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hsindex 3ebfa57..3c47e0c 100644--- a/src/Radicle/Internal/Pretty.hs+++ b/src/Radicle/Internal/Pretty.hs@@ -74,6 +74,12 @@ instance Pretty r => Pretty (LangErrorData r) whereParseError t -> "Parser error:" <+> pretty (parseErrorPretty t)Exit -> "Exit"ThrownError i val -> "Exception" <+> pretty i <+> pretty val+ PatternMatchError e -> case e of+ NoMatch -> "Pattern match(es) are non-exhaustive."+ NoValue -> "The `match` special form must be given a value to match on."+ BadBindings p -> "Faulty pattern function. Pattern functions must return\+ \ `[:Just b]` where `b` is a dict of new bindings (from\+ \ atoms to values), or `:Nothing`:" <+> pretty p-- | A fast and compact layout. Primarily intended for testing.diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hsindex ed286f2..551f0e1 100644--- a/src/Radicle/Internal/PrimFns.hs+++ b/src/Radicle/Internal/PrimFns.hs@@ -222,6 +222,15 @@ purePrimFns = fromList $ allDocs $pure (Vec (fst <$> ys'))_ -> throwErrorHere $ TypeError "sort-by: second argument must be a sequence")+ , ( "zip"+ , "Takes two sequences and returns a sequence of corresponding pairs. In one\+ \ sequence is shorter than the other, the excess elements of the longer\+ \ sequence are discarded."+ , twoArg "zip" $ \case+ (Vec xs, Vec ys) -> pure $ Vec (pair <$> Seq.zip xs ys)+ (List xs, List ys) -> pure $ List (pair <$> zip xs ys)+ _ -> throwErrorHere $ TypeError "zip: only works on vectors or lists"+ )-- Dicts, ("lookup"@@ -252,7 +261,7 @@ purePrimFns = fromList $ allDocs $(List xs, List ys) -> pure $ List (xs ++ ys)(Vec xs, Vec ys) -> pure $ Vec (xs Seq.>< ys)(Dict m, Dict n) -> pure $ Dict (n <> m)- _ -> throwErrorHere $ TypeError "<>: only works on vectors of dicts"+ _ -> throwErrorHere $ TypeError "<>: only works on vectors or dicts"), ( "string-length"@@ -371,6 +380,12 @@ purePrimFns = fromList $ allDocs $, oneArg "list?" $ \caseList _ -> pure tt_ -> pure ff)+ , ( "vector?"+ , isTy "vector"+ , oneArg "vector?" $ \case+ Vec _ -> pure tt+ _ -> pure ff+ ), ( "dict?", isTy "dict", oneArg "dict?" $ \case@@ -418,7 +433,7 @@ purePrimFns = fromList $ allDocs $[x, Vec xs] -> pure . Boolean . isJust $ Seq.elemIndexL x xs[x, Dict m] -> pure . Boolean $ Map.member x m[_, _] -> throwErrorHere- $ TypeError "member?: second argument must be list"+ $ TypeError "member?: second argument must be list, vector or dict"xs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs)), ( "ref", "Creates a ref with the argument as the initial value."@@ -509,6 +524,12 @@ purePrimFns = fromList $ allDocs $fromMaybe ("No documentation found for " <> fromIdent i <> ".") d_ -> throwErrorHere $ OtherError "doc: expects an atom")+ , ( "match-pat"+ , "The most basic built-in pattern-matching dispatch function."+ , twoArg "match-pat" $ \case+ (x@(Atom _), v) -> pure $ toRad (Just (Dict (Map.singleton x v)))+ (pat, v) -> callFn pat [v]+ )]whereisTy t = "Checks if the argument is a " <> t <> "."@@ -523,6 +544,9 @@ purePrimFns = fromList $ allDocs $kw = Keyword . Ident+ pair :: (Value, Value) -> Value+ pair (x,y) = Vec (x :<| y :<| Empty)+numBinop :: (Rational -> Rational -> Rational)-> Text-> Text