Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lists:foreach returns ok in Erlang

Tags:

erlang

I have just started in Erlang and find it difficult to understand. I want to split a list into a string, run string:titlecase on it, and join it into a string.

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

but it fails with the error message escript: exception error: no function clause matching lists:join(" ",ok) (lists.erl, line 1449) because it returns ok, Why does it return ok?

like image 642
Ron Nnn Avatar asked Dec 24 '22 03:12

Ron Nnn


1 Answers

lists:foreach doesn't return the value that the function passed to it returns. It's meant to be used with functions that only cause side effects (e.g. printing). You're looking for 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"]

And also, the anonymous function can be made shorter using fun module:name/arity syntax:

4> lists:join(" ", lists:map(fun string:titlecase/1, TextArray)).
["Foo"," ","Bar"," ","Baz"]
like image 126
Dogbert Avatar answered Jan 02 '23 16:01

Dogbert