Skip to content

Instantly share code, notes, and snippets.

@coder054
Forked from iain17/words.erl
Created September 19, 2022 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coder054/15f04d84111ed64c438d1fade0fe94d5 to your computer and use it in GitHub Desktop.
Save coder054/15f04d84111ed64c438d1fade0fe94d5 to your computer and use it in GitHub Desktop.
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