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?
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With