问题
I have a couple of classes (namely book and user). I need to update a book by setting its lended slot to t and its lended-to to the borrower's id.
I'm using Postmodern as a back-end to a PostgreSQL database
This is what I came up with (I hope the names are self-describing enough)
(defmethod lend-book ((to-lend book) borrower) ;borrower is a user instance
(if (book-lent to-lend)
nil
(let (to-lend (get-dao 'book (book-id to-lend)))
(setf (book-lent-to to-lend) (user-id borrower))
(setf (book-lent to-lend) t)
(update-dao to-lend))))
But it seems too much imperative to me.
Is there a more functional way to do this or does Postmodern get in the way?
回答1:
You are modifying state, so that's what you write. I see this as idiomatic.
I just see two problems with your code:
- Your
defmethodhas its lambda list mixed up: it should be(to-lend book), not the other way around. This should give some warnings or errors. - The participle of "lend" is "lent", so the slots should be named
book-lentandbook-lent-to.
来源:https://stackoverflow.com/questions/6723173/updating-a-postmodern-row-in-a-more-functional-way