Skip to content

Instantly share code, notes, and snippets.

@iain17 iain17/words.erl
Last active Apr 6, 2017

Embed
What would you like to do?
Write a function that uses recursion to return the number of words in a string.
-module(words).
-export([strlen/1]).
%Assignment: Write a function that uses recursion to return the number of words in a string.
% If we send an empty list, return 0.
strlen([]) -> 0;
%Entry point for this module
strlen(Sentence) -> count(Sentence, 1).
%Base case. When its finally empty return the sum count.
count([], Count) -> Count;
%Use a pattern with 32 (ascii 32 is a space) and keep calling untill you hit the above method.
count([32|Tail], Count) -> count(Tail, Count + 1);
%This method takes the last character saves it as a variable called Tail and calls count.
%The _ is because we don't care about the first part.
count([_|Tail], Count) -> count(Tail, Count).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.