Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

good style in lisp: cons vs list

Is it good style to use cons for pairs of things or would it be preferable to stick to lists?

like for instance questions and answers:

(list
    (cons
        "Favorite color?"
        "red")
    (cons
        "Favorite number?"
        "123")
    (cons
        "Favorite fruit?"
        "avocado"))

I mean, some things come naturally in pairs; there is no need for something that can hold more than two, so I feel like cons would be the natural choice. However, I also feel like I should be sticking to one thing (lists).

What would be the better or more accepted style?

like image 225
user1076329 Avatar asked Dec 09 '22 19:12

user1076329


1 Answers

What you have there is an association list (alist). Alist entries are, indeed, often simple conses rather than lists (though that is a matter of preference: some people use lists for alist entries too), so what you have is fine. Though, I usually prefer to use literal syntax:

'(("Favorite color?" . "red")
  ("Favorite number?" . "123")
  ("Favorite fruit?" . "avocado"))

Alists usually use a symbol as the key, because symbols are interned, and so symbol alists can be looked up using assq instead of assoc. Here's how it might look:

'((color . "red")
  (number . "123")
  (fruit . "avocado"))
like image 81
Chris Jester-Young Avatar answered Dec 11 '22 08:12

Chris Jester-Young