hatlog icon indicating copy to clipboard operation
hatlog copied to clipboard

Use higher-order predicates for more convenience

Open triska opened this issue 9 years ago • 4 comments

The following two higher-order predicates may turn out very helpful, also in future extensions:

  • maplist/3, for example in: maplist(pretty_type, Ls0, Ls), avoiding an auxiliary predicate
  • foldl/4 to avoid or shorten replace_vars_/6

I hope this helps to make the code a bit shorter and more readable.

triska avatar Jun 09 '16 19:06 triska

Oh, those are great, I'll refactor it tomorrow!

Also, do you know if this free var manipulation (detecting free vars and replacing them with atoms) is something which is normal in Prolog or is there a more idiomatic way to do it?

alehander92 avatar Jun 09 '16 20:06 alehander92

The best way to reason about variables within your program is to choose a good representation for your data. In an initial conversion step, you will likely need impure checks like var/1 to detect variables, but you can convert this to a cleaner representation by distinguishing variables with a suitable wrapper. You can for example use v(Var), var(Var) or variable(Var) to represent variables within your data, and a(Atom) or atom(Atom) to represent atoms.

Throughout the remainder of your program, you can simply distinguish the cases symbolically:

some_predicate(a(Atom)) :- ...
some_predicate(v(Var))  :- ...

triska avatar Jun 10 '16 06:06 triska

That's a pretty cool trick, another thing I wondered is how prolog-y is using dicts (I used assoc lists, because I wanted to support SWI 6, so I guess dicts are a recent addition, but on the other side dict data structures are very popular in most other languages lately, including lisps: Clojure)

alehander92 avatar Jun 10 '16 08:06 alehander92

Association lists are a fine and also very portable way to do such lookups, and their performance is often completely acceptable.

Dicts may be useful if you do a let of web programming and JSON interactions, but they will chain you to a specific Prolog system.

triska avatar Jun 10 '16 08:06 triska