list:foreach在Erlang中返回确定

时间:2018-09-26 19:43:56

标签: erlang

我刚开始在Erlang学习,很难理解。 我想将列表拆分为字符串,对其运行string:titlecase,然后将其加入字符串。

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

,但失败,并显示错误消息escript: exception error: no function clause matching lists:join(" ",ok) (lists.erl, line 1449),因为它返回了ok, 为什么返回正常?

1 个答案:

答案 0 :(得分:9)

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"]