gpt4 book ai didi

erlang - 列出 :foreach returns ok in Erlang

转载 作者:行者123 更新时间:2023-12-01 16:30:34 25 4
gpt4 key购买 nike

我刚开始接触Erlang,觉得很难理解。我想将列表拆分为字符串,对其运行 string:titlecase,然后将其连接到字符串中。

namecase(Text) ->
TextArray = string:split(Text, " ", all),
lists:join(" ", lists:foreach(fun(Element) -> string:titlecase(Element) end, TextArray)).

但它失败并显示错误消息escript:异常错误:没有与lists匹配的函数子句:join(“”,ok)(lists.erl,第1449行)因为它返回ok ,为什么返回正常?

最佳答案

lists:foreach 不返回传递给它的函数返回的值。它旨在与只会引起副作用的功能(例如打印)一起使用。您正在寻找lists:map

1> Text = "foo bar baz".
"foo bar baz"
2> TextArray = string:split(Text, " ", all).
["foo","bar","baz"]
3> lists:join(" ", lists:map(fun(Element) -> string:titlecase(Element) end, TextArray)).
["Foo"," ","Bar"," ","Baz"]

此外,可以使用 fun module:name/arity 语法使匿名函数更短:

4> lists:join(" ", lists:map(fun string:titlecase/1, TextArray)).
["Foo"," ","Bar"," ","Baz"]

关于erlang - 列出 :foreach returns ok in Erlang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52525050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com