有没有一种方法可以从Clojure中另一个函数的列表中创建函数中的字符串



我对Clojure和函数式编程很陌生,我试图使用两个函数来连接字符串中的一些字符。我的想法基本上是这样的:

(defn receive [char-from-list]
(str char-from-list))
(defn send-char [list-char]
(if (empty? list-char)
(receive nil)
((receive (first list-char))(send-char (rest list-char)))))

因此,我的想法是,我从send函数开始,作为一个参数,写一个字符列表,如下所示:

(send-char '(h e l l o))

带有get的receive函数一次发送一个字符,并使用str将它们全部添加在一起,我的最终输出将是:";你好";。

当我尝试运行代码时,会出现以下错误:automa.core/send-char(core.clj:44(处的执行错误(ClassCastException(。类java.lang.String不能强制转换为类clojure.lang.IFn(java.lang.Sstring在加载程序'bootstrap'的模块java.base中;clojure.log.IFn在加载程序'app'的未命名模块中(

我不确定是否有办法做到这一点或另一种方法,但我不知道如何做到,请帮忙。感谢

错误是因为这里有两个左括号:

((receive ...

记住,在Clojure中,左paren的意思是";函数调用";,并且字符串不是函数(函数receive返回字符串(。

如果您有两个要在Clojure中分组的东西,则需要使用do形式,如:

(defn send-char [chars]
(if (empty? chars)
(receive nil)
(do
(receive (first chars))
(send-char (rest chars)))))

在确定了错误的来源后,您最初的问题仍然非常模糊和未定义。以下是将一系列字符连接成字符串的3种方法:

(ns tst.demo.core
(:use tupelo.core tupelo.test)
(:require
[clojure.string :as str]))
(dotest
(let-spy [chars (vec "hello")
s0 (apply str chars)
s1 (str/join chars)
s2 (reduce str "" chars)
]
(is= chars [h e l l o])
(is= s0 "hello")
(is= s1 "hello")
(is= s2 "hello")
))

以上是基于我最喜欢的模板项目。一定要研究文档来源的列表。

相关内容

最新更新