]> gitweb.factorcode.org Git - factor.git/commitdiff
assocs: adding ?value-at.
authorJohn Benediktsson <mrjbq7@gmail.com>
Thu, 16 Jun 2022 16:40:02 +0000 (09:40 -0700)
committerJohn Benediktsson <mrjbq7@gmail.com>
Thu, 16 Jun 2022 16:40:02 +0000 (09:40 -0700)
core/assocs/assocs-docs.factor
core/assocs/assocs.factor

index 34e637ced70b7287585eb358ae0354fe99a17e79..66cea3395ab227dff7654e3e6829b3b473000919 100644 (file)
@@ -74,6 +74,8 @@ ARTICLE: "assocs-lookup" "Lookup and querying of assocs"
     ?at
     of
     ?of
+    value-at
+    ?value-at
     assoc-empty?
     keys
     values
@@ -402,6 +404,10 @@ HELP: value-at
 { $values { "value" object } { "assoc" assoc } { "key/f" { $maybe "the key associated to the value" } } }
 { $description "Looks up the key associated with a value. No distinction is made between a missing key and a key set to " { $link f } "." } ;
 
+HELP: ?value-at
+{ $values { "value" object } { "assoc" assoc } { "key/value" "the key associated to the value or the value if the value is not present in the assoc" } { "?" "a " { $link boolean } " indicating if the value was present" } }
+{ $description "Looks up the key associated with a value. If the value was not present, an error can be thrown without extra stack shuffling. This word handles assocs that store " { $link f } "." } ;
+
 HELP: value?
 { $values { "value" object } { "assoc" assoc } { "?" boolean } }
 { $description "Tests if an assoc contains at least one key with the given value." } ;
index 003b2a4a1a0a41181908735a64d62af7be1e3c32..f3ee6b32c06526b0682dfe713baadb54ea5f8118 100644 (file)
@@ -221,6 +221,9 @@ M: assoc value-at* swap [ = nip ] curry assoc-find nip ;
 
 : value-at ( value assoc -- key/f ) value-at* drop ;
 
+: ?value-at ( value assoc -- key/value ? )
+    2dup value-at* [ 2nip t ] [ 2drop f ] if ; inline
+
 : value? ( value assoc -- ? ) value-at* nip ;
 
 : push-at ( value key assoc -- )