Skip to content

Instantly share code, notes, and snippets.

@iain17
Last active September 19, 2022 10:06
Show Gist options
  • Save iain17/ca584179f2009330a7bd58252d082b22 to your computer and use it in GitHub Desktop.
Save iain17/ca584179f2009330a7bd58252d082b22 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