【问题标题】:Racket: Apply string-replace to list球拍:将字符串替换应用于列表
【发布时间】:2021-03-20 15:58:55
【问题描述】:
 (apply string-replace ";" "" '("a" "b;" "c"))

给我错误信息

string-replace: arity mismatch;
the expected number of arguments does not match the given number
expected: 3 plus an optional argument with keyword #:all?
given: 5
arguments...:

据我了解,问题在于列表是 consed 到 string-replace 函数的参数,而我想 apply 函数到列表的每个元素。

applystring-replace 到列表的正确方法是什么?

(apply string-replace "b" "" '("b;"))

有效,但返回"b;bb;,而我本来期望"b"

【问题讨论】:

    标签: functional-programming scheme racket


    【解决方案1】:

    要将函数应用于列表的所有元素,请使用map (reference):

    (map (lambda (str) (string-replace str ";" ""))
         '("a" "b;" "c"))
    

    生产

    '("a" "b" "c")
    

    【讨论】:

    • 非常感谢,这行得通!为了理解答案:为什么像(apply + '(1 2 3)) 这样的东西不需要map
    • 因为您正在应用一个可以接收 list 参数的函数 (+)(因此您可以编写 (+ 1 2 3))。而在string-replace 的情况下,该函数只需要一个 字符串参数。因此,如果要将其应用于参数列表,则必须为每个参数“重复”该应用程序。
    • 感谢您的解释。我并没有真正理解这个基本概念。 stackoverflow.com/questions/27488723/…> 更详细地解释它。
    • 其实如果你看答案中的例子,你可以看到应用于列表的函数不是string-replace,而是(lambda (str) (string-replace str ";" ""))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2021-08-02
    • 2013-05-01
    • 2016-12-24
    相关资源
    最近更新 更多