微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法从 Clojure 中另一个函数中的列表创建一个函数中的字符串?

如何解决有没有办法从 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 的接收函数一次发送一个字符,并使用 str 将它们加在一起,我的最终输出将是:“hello”。

当我尝试运行代码时出现此错误 automata.core/send-char (core.clj:44) 处的执行错误 (ClassCastException)。 类 java.lang.String 不能转换为类 clojure.lang.IFn(java.lang.String 位于加载器“bootstrap”的 java.base 模块中;clojure.lang.IFn 位于加载器“app”的未命名模块中)

我不确定是否有办法做到这一点或其他方法,但我不知道如何,请帮助。谢谢

解决方法

错误是因为您在这里连续有 2 个左括号:

((receive ...

记住,在 Clojure 中,左括号表示“函数调用”,字符串不是函数(函数 receive 返回字符串)。

如果您想在 Clojure 中对 2 个事物进行分组,则需要使用 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")
    ))

以上基于my favorite template project。一定还要研究list of documentation sources

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。