You can use car
to retrieve the first element in the output list, but I don't think filter-map
is the best option here - after all you're not interested in the list of results returned by filter-map
, only in a single element - and this is unavoidable, a list will be returned even if it's empty. Basically, you need to look for a value in an association list. Try this instead:
(cdr (assq 'z (map cons list1 list2)))
=> 'bla
Explanation:
(map cons list1 list2)
builds an association list, where the elements inlist1
are the keys and the elements inlist2
are the valuesassq
looks for the key-value pair that has'z
as its key (usingeq?
for the comparisons), and returns that paircdr
returns the value part of that pair
Alternatively, you can check if your interpreter has a hash table implementation available (useful if you have to efficiently perform more than one search), for instance in Racket:
(hash-ref (make-hasheq (map cons list1 list2)) 'z)
=> 'bla
Explanation:
(map cons list1 list2)
builds an association list, where the elements inlist1
are the keys and the elements inlist2
are the valuesmake-hasheq
creates a new hash table using the association list, and useseq?
when finding a value given the keyhash-ref
returns the value corresponding to the key'z
Be aware that both of the above options will raise an error when we attempt to obtain the value if the key wasn't present in list1
, you have to decide how to handle this case if the need arises; for example we can return #f
:
(let ((pair (assq 'z (map cons list1 list2))))
(and pair (cdr pair)))
(hash-ref (make-hasheq (map cons list1 list2)) 'z
(const #f))