1

我刚开始使用clojure,我正在做一个有趣的项目。在下面的函数中,我只是想显示一些博客文章(带有一些选项)。使用“as”选项,我想让客户端代码能够在 vector[]和 map之间进行选择{}(into [] results)我只有(when). 我想(when)只是返回nil,因为它就像一个隐含的(do). 现在对我来说很明显,(when)像这样在末尾使用是结束您希望返回值的函数的错误方法。我怎样才能让它工作?

(ns yf.models.post
  (:require [clojure.java.jdbc :as sql]
            [clojure.string :as str])
  (:use [yf.models.helpers :only [date-format]]))


(defn all [& {:keys [order limit roots-only as]}]
  (sql/with-connection (System/getenv "DATABASE_URL")
    (sql/with-query-results results
      [(str 
        "SELECT
          id,
          body,"
          (date-format "created") ","
          (date-format "modified")
        "FROM post a"
        (when (true? roots-only)
          " WHERE NOT EXISTS (SELECT child_id from post_map b
                          WHERE a.id=b.child_id) ")
        (when (and
                (string? (order :column))
                (string? (order :dir))
                (or 
                  (= (:dir order) "asc")
                  (= (:dir order) "desc")))
          (str " ORDER BY a." (:column order) " " (:dir order)))
        (when (and
                (instance? Number limit)
                (pos? limit))
          (str " LIMIT " limit)))]
      (when (and                     ;this is where the problem is
              (string? as)
              (not (str/blank? as)))
        (when (= as "vector")
          (into [] results))
        (when (= as "map")
          (into {} results))))))
4

1 回答 1

4

问题不在于(when)总是返回nil——它并不总是返回nil;它返回表达式集合中最后的任何内容。(when)是一个使用 ' 的宏,(if)(do)这正是(do)它的作用:执行表达式列表并返回集合中最后一个表达式的值。

我尝试了(case)宏,它可以工作:

...
(case as
  "vector" (into [] results)
  "map" (into {} results))

或者,更好(感谢 kotarak):

(into (empty as) results)

哪里asvector"vector"我认为与 相反)

于 2012-10-21T20:34:09.567 回答