# How about predefined dict function Dict.get(Key, Default)

**URL:** <https://swi-prolog.discourse.group/t/how-about-predefined-dict-function-dict-get-key-default/1314>\
**Category:** Request For Comments\
**Created:** [September 25, 2019, 9:01pm UTC](https://swi-prolog.discourse.group/t/how-about-predefined-dict-function-dict-get-key-default/1314 "2019-09-25T21:01:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nuclear\_ares](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/nuclear_ares/32/144_2.png) [@nuclear\_ares](https://swi-prolog.discourse.group/u/nuclear_ares)\
**Post date:** [September 25, 2019, 9:01pm UTC](https://swi-prolog.discourse.group/t/how-about-predefined-dict-function-dict-get-key-default/1314/1 "2019-09-25T21:01:24Z")

</div>

Implementing it myself works, but forces me to use a specific tag for the dict.

```prolog
M.get(Key, Default) := Val :-
    ( Val = M.get(Key), !
    ; Val = Default).

```

get\_dict/4 doing ~the same would IMO also be a good addition.

Or did I just miss some convenient shortcut / already present way to do this \>

---

<div class="post-metadata">

**Author:** ![jan](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/jan/32/4_2.png) [@jan](https://swi-prolog.discourse.group/u/jan)\
**Post date:** [September 28, 2019, 4:07pm UTC](https://swi-prolog.discourse.group/t/how-about-predefined-dict-function-dict-get-key-default/1314/2 "2019-09-28T16:07:19Z")

</div>

As is, tags are tight to modules when using user defined functions on dicts. I have my doubt on whether you want to allow for functions on dicts regardless of the tag. That would eliminate all modularity.

So, I’m afraid the answer is no. Of course you can hack in the implementation 🙂

P.s. this is teh second time in a relatively short period that I see `(A, !; B)`. Where does this come from, rather than the normal `(A->true;B)`?

P.s. One should avoid unification of arguments before a ! or -\>. As is, if the dict has a value different from the default but you ask it with the output instantiated to the default it will succeed. Use

```prolog
M.get(Key, Default) := Val :-
    ( Val0 = M.get(Key)
    -> Val = Val0
    ; Val = Default
    ).

```

---

<div class="post-metadata">

**Author:** ![esad](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/esad/32/884_2.png) [@esad](https://swi-prolog.discourse.group/u/esad)\
**Post date:** [December 2, 2020, 11:38pm UTC](https://swi-prolog.discourse.group/t/how-about-predefined-dict-function-dict-get-key-default/1314/3 "2020-12-02T23:38:00Z")

</div>

I must admit that `Foo = Dict.get(foo, default)` is nicer than `(Foo = Dict.get(foo) -> true ; Foo = default)`, especially because `get`s can be chained. Isn’t this use case common enough to grant addition of `get/2` (and a matching `get_dict/4`) to the library?
