次のコードを検討してください。
(if-let [x (a-function)]
(do-something-with x) ;; (a-function) returned a truthy result
(do-something-else) ;; (a-function) returned nil or false
これは のようなものletで、xの戻り値にバインドされます(a-function)。この関数はnil、 またはを返しfalseます。その場合、暗黙のテストは失敗し、(do-something-else)評価されます。xis notnilおよび notfalseの場合は(do-something-with x)評価されます。
これが役立つシナリオ:
(if-let [user (find-logged-in-user)]
(do something with logged in user) ;; a user was found
(redirect to login page) ;; no user was found
オプションのマップに条件付きでキーを追加するために、次のようなものを使用することがあります。
(apply merge {:username "joe"
:email "joe@example.com"}
(when-let [name (find-full-name)] {:name name})
(when-let [dob (find-date-of-birth)] {:dob dob}))
:usernameこれにより、と:emailキーを含むマップが作成され:name、ユーザーの氏名が見つかった:dob場合はキーが、生年月日が見つかった場合はキーが作成されます。
if-letそれが使いやすく、when-letより明確になることを願っています。