-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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