From 1df27928381eb21e043f57af019884aa27ad3aa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Pant=C5=AF=C4=8Dek?= Date: Sun, 9 Apr 2023 19:34:27 +0200 Subject: [PATCH] Implement ldict-ref. --- doc/utils.md | 11 +++++++++++ src/util-dict.scm | 17 ++++++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/doc/utils.md b/doc/utils.md index a5358fa..c992cbf 100644 --- a/doc/utils.md +++ b/doc/utils.md @@ -62,6 +62,17 @@ Returns ```#t``` if given dictionary contains no keys. Returns ```#t``` if given ```ld``` contains given key ```k```. + (ldict-ref ld k [default]) + +* ```ld``` - a ldict instance +* ```k``` - a compatible key +* ```default``` - optional fallback value + +Retrieves the value associated with given key in given dictionary. If +the dictionary does not contain it and no default is given, an +exception is raised. Otherwise the default value is returned in case +of missing key. + ### IO (import util-io) diff --git a/src/util-dict.scm b/src/util-dict.scm index af91ba9..27448f9 100644 --- a/src/util-dict.scm +++ b/src/util-dict.scm @@ -97,13 +97,16 @@ ;; is provided it is used as default value in case the key does not ;; exist. If only two arguments are given and the key does not exist, ;; raises an error. - (define (dict-ref d k . r) - (let ((p (assq k d))) - (if p - (cdr p) - (if (null? r) - (error 'dict-ref "Key does not exist" k) - (car r))))) + (define (ldict-ref ld k . ds) + (let ((equality? (ldict-equality? ld))) + (let loop ((pairs (ldict-pairs ld))) + (if (null? pairs) + (if (null? ds) + (error 'ldict-ref "Key does not exist" k) + (car ds)) + (if (equality? (caar pairs) k) + (cdar pairs) + (loop (cdr pairs))))))) ;; Returns a new dictionary based on d with key k removed. If it ;; doesn't contain the key, an error is raised.