Search code examples
listlispcommon-lisphashtable

Mapping two string lists (in a short way) in Lisp?


Lisp beginner here.

I have two string lists in this form with same length:

  keys = ("abc" "def" "gh" ...)
  values = ("qwe" "opr" "kmn" ...)

I need to construct hash-table or association lists (whichever is easy to construct and fast to get values from) from those lists. They are in the proper index due to their pair.

I know I can map them with iterating. But I want go with a more declarative way and I am looking for a clean way to this, if it can be done so.


Solution

  • There is a dedicated function named PAIRLIS that does exactly what what you want to build association lists:

    USER> (pairlis '("abc" "def" "gh")
                   '("qwe" "opr" "kmn"))
    (("gh" . "kmn") ("def" . "opr") ("abc" . "qwe"))
    

    Note that the order is reversed, but this depends on the implementation. Here orders does not matter since your keys are unique.

    Then, you can use the popular alexandria library to build a hash-table from that:

    USER> (alexandria:alist-hash-table * :test #'equalp)
    #<HASH-TABLE :TEST EQUALP :COUNT 3 {101C66ECA3}>
    

    Here I am using a hash-table with test equalp because your keys are strings.

    NB. The * symbol refers to the last primary value in a REPL