Reputation: 20633
I'm reading the "Seven Languages in Seven Weeks" book, and can't pass a little issue in the day one erlang's self-study.
My code is something like this:
-module(slsw).
-export([count_words/1]).
list_length([]) -> 0;
list_length(String) ->
[_ | Tail] = String,
1 + list_length(Tail).
count_words(Text) ->
{_, R} = re:split(Text, " "),
list_length(R).
But, when I open erl
, compile it (c(slsw).
), and try to use it with something like this:
slsw:count_words("yoo dude, this is a test").
I got this annoying runtime exception:
** exception error: no match of right hand side value [<<"yoo">>,<<"dude,">>,<<"this">>,<<"is">>,<<"a">>,
<<"test">>]
in function slsw:count_words/1 (slsw.erl, line 19)
Looks like it end the array, then throw this exception.. what am I doing wrong?
I also found the string:words
function, but I want to do my own for fun/study.
Thanks in advance
Upvotes: 2
Views: 10310
Reputation: 2173
I don't believe re:split/2 returns a tuple - it returns a list. So, your {_, R} = re:split/2 two line errors out because the return of the function cannot match the tuple on the left hand side of the =
Upvotes: 2
Reputation: 2612
re:split/2
just returns a list, instead of a tuple. It may be a typo in the Book's text.
Admittedly, Erlang error messages can be a tad cryptic to folks new to the language, but the hint that can help you read the error message is that it's saying the right hand side of the equals sign evaluates to [<<"yoo">>,<<"dude,">>,<<"this">>,<<"is">>,<<"a">>,<<"test">>]
(simply the return value from re:split - ie, a list of binaries), and it's unable to match that with the 2-tuple on the left.
So if you simply changed your count_words
function to the following, that should be sufficient:
count_words(Text) ->
R = re:split(Text, " "),
list_length(R).
Upvotes: 3