首页 > 解决方案 > Clojure:您可以将 Concat 与其他非常复杂的函数一起使用吗?

问题描述

(ns untitled1.core
  (:require [clojure.string :as str]))

(defn nottrue                              ;helper function for below function
 [inp]
 (not (true? inp))
 )

(defn and-simplify 
"function that, for example, takes: (and-simplify '(and true false)) and evaluates it -> false. 
This function works perfectly if called directly from REPL."
  [last]

  (cond
(some false? last) false
(every? true? (rest last)) true
(= 1 (count (filter nottrue (rest last)))) (let [xyz (filter nottrue (rest last))] xyz)
:else (let [xxx (filter nottrue last)] xxx)
) )


(defn concact_function 
"When the user types: (concact_function '(and false true) '(and true true true false)). It should
return -> Concacted Version: (and true true true false)"
  [my_expression original]

   (println "Concacted Version: " (concat (drop-last original) (and-simplify my_expression)))
  )

当我输入: (concact_function '(and false true) '(and true true true false))

这将返回:untitled1.core/concact-function (core.clj:26) 处的执行错误 (IllegalArgumentException)。不知道如何从:java.lang.Boolean Concacted Version 创建 ISeq:(并且 true

我做了一些调试,发现问题出在我尝试联系(并简化我的表达式)时。And-simplify 在直接调用时完全按照它应该做的方式工作,但由于某种原因不喜欢联系。

(我实际上不需要打印它,我只需要返回它以进行进一步操作。但我打印它是为了可视化)

标签: clojureevaluation

解决方案


concat函数适用于集合,该函数and-simplify仅返回一个布尔值。要解决此问题,您可以将整个 cond 子句放入向量或列表中,或者将每个 cond 子句的返回值放入向量中。

通过以下修复:

    (defn and-simplify 
      "function that, for example, takes: (and-simplify '(and true false)) and evaluates it -> false. 
      This function works perfectly if called directly from REPL."
      [last]
      [(cond
          (some false? last) false
          (every? true? (rest last)) true
          (= 1 (count (filter nottrue (rest last)))) (let [xyz (filter nottrue (rest last))] xyz)
          :else (let [xxx (filter nottrue last)] xxx)
          )])

将返回预期结果: Concacted Version: (and true true true false)


推荐阅读