RSS Feed

Lisp Project of the Day

place-modifiers

You can support this project by donating at:

Donate using PatreonDonate using Liberapay

Or see the list of project sponsors.

place-modifiersmacrodata-structures

Documentation😀
Docstrings😀
Tests 😀
Examples😀
RepositoryActivity🥺
CI 🥺

This is a library by @HexstreamSoft. It provides a shorthand macro to modify data-structures in place.

The library has comprehensive documentation so, I'll only show you one example to demonstrate how it works.

Let's pretend we have some data received from an API and "age" field should be converted into the integer in place.

In plain CL we'll do it like this:

POFTHEDAY> (let ((data
                   '#((:name "Bob" :params (:age "45"))
                      (:name "Alice" :params (:age "23")))))
             (loop for item across data
                   do (setf (getf (getf item :params)
                                  :age)
                            (parse-integer
                             (getf (getf item :params)
                                   :age))))
             data)
#((:NAME "Bob" :PARAMS (:AGE 45)) (:NAME "Alice" :PARAMS (:AGE 23)))

But place-modiifiers allows you to keep your code DRY:

POFTHEDAY> (let ((data
                   '#((:name "Bob" :params (:age "45"))
                      (:name "Alice" :params (:age "23")))))
             (loop for item across data
                   do (place-modifier:modify
                       (parse-integer
                        (getf (getf item :params)
                              :age))))
             data)
#((:NAME "Bob" :PARAMS (:AGE 45)) (:NAME "Alice" :PARAMS (:AGE 23)))

Here I've extracted forms responsible for the modification:

;; Plain Common Lisp
(setf (getf (getf item :params)
            :age)
      (parse-integer
       (getf (getf item :params)
             :age)))

;; Using Place Modifiers macro
(place-modifier:modify
 (parse-integer
  (getf (getf item :params)
        :age)))

To learn more about place-modifiers, read it's docs! There is a lot of examples.

You might also be interested in reading the post about access library.


Brought to you by 40Ants under Creative Commons License