I'm going over past exams studying for my upcoming exam, and after completing a couple of the questions I came across one that I couldn't solve.
It wants a function that will take a String (or [Char]) and return an Int of the number of english words that are in the String. It says that isWord is a hypothetical function that takes a String and returns a Boolean depending on if the word is true or false. The words must be in a row, left to right. The example given was "catalogre". So "cat", "at", "catalog", "ogre" and "log", the function should return 5.
wordsInString :: [Char] -> Int
wordsInString [] = 0
wordsInString x
| isWord (take 1 x)
| isWord (take 2 x)
The bumpers are just showing what I was thinking, obviously it wont work.
This is how I started, and I was thinking that I could use the take
function and increment it each letter at a time, then move the starting letter down until []
, but I wasn't sure how to implement that recursion correctly. If anyone has any ideas or could show me a way, it would be great.
If you know how to distinguish word from non-word you can use inits
and tails
to get list of all possible candidates:
> :m +Data.List
> concatMap inits $ tails "catalogre"
["","c","ca","cat","cata","catal","catalo","catalog","catalogr","catalogre","","a","at","ata","atal","atalo","atalog","atalogr","atalogre","","t","ta","tal","talo","talog","talogr","talogre","","a","al","alo","alog","alogr","alogre","","l","lo","log","logr","logre","","o","og","ogr","ogre","","g","gr","gre","","r","re","","e",""]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With