A dictionary based on Sterling and Shapiro #2641
dnmfarrell
started this conversation in
Show and tell
Replies: 1 comment 2 replies
-
Have you seen |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hey all
This is a tale of what happened yesterday that resulted in dict.pl. I'd love to hear any feedback you might have on the code, I'll probably blog about it.
Yesterday I was using scryer prolog to process a stream of data that I needed to compute statistics on. Naturally I needed a dictionary, so I started with program 15.9 from The Art of Prolog, with a couple of updates:
Since we have
compare/3
and a pair type, I updated program 15.9 to:But this leaves behind a choicepoint, so:
And I was quite smitten with this.
But then I found I needed to check for the existence of a key:
lookup(K, D, V), nonvar(V).
so I createdget/3
to do that.And since
get/3
was semantically clearer thanlookup/3
, I createdadd/3
to complement it.And I was done!
Or so I thought, but then I needed to update a key. This stumped me as I tried and failed to use list differences to modify a pair without copying the tree. I gave in and added
put/4
to update and return a copy.This thing was getting dangerously useful - but did it work? I wrote
to_list/2
which made writing tests and debugging easy, and to my astonishment it was un-moded so I renamed itdict_list
(careful how you say that!) and I could transform a list of pairs into a dictionary or vice-versa.And this worked great and I finished my prolog data processor. Even better, it found bugs in my previous data processor.
Then the prospect of the tree getting unbalanced and
O(n)
operations started to weigh heavy on me 😰How could I live with such terrible risks?
I practically yelled with joy when I realized I could use
keysort/2
to balance the tree. Eureka!And I got a good night's sleep.
Beta Was this translation helpful? Give feedback.
All reactions