I’ve got a problem about to write a function to find the longest word in a text.
Input: A string with a lot of word. Ex: "I am a young man, and I have a big house."
The result will be 5 because the longest words in the text have 5 letters (young and house).
I’ve just started to learn Haskell. I’ve tried:
import Char
import List
maxord' (str:strs) m n =
if isAlpha str == True
then maxord'(strs m+1 n)
else if m >= n
then maxord'(strs 0 m)
else maxord'(strs 0 n)
maxord (str:strs) = maxord' (str:strs) 0 0
I want to return n as the result but I don’t know how to do it, and it seems there is also something wrong with the code.
Any help? Thanks
There are several issues here. Let’s start with the syntax.
Your
elseparts should be indented the same or more as theifthey belong to, for example like this:Next, your function applications. Unlike many other languages, in Haskell, parentheses are only used for grouping and tuples. Since function application is so common in Haskell, we use the most lightweight syntax possible for it, namely whitespace. So to apply the function
maxord'to the argumentsstrs,m+1andn, we writemaxord' strs (m+1) n. Note that since function application has the highest precedence, we have to add parentheses aroundm+1, otherwise it would be interpreted as(maxord' strs m) + (1 n).That’s it for the syntax. The next problem is a semantic one, namely that you have recursion without a base case. Using the pattern
(str:strs), you have specified what to do when you have some characters left, but you’ve not specified what to do when you reach the end of the string. In this case, we want to returnn, so we add a case for that.The fixed
maxord'is thusHowever, note that this solution is not very idiomatic. It uses explicit recursion,
ifexpressions instead of guards, comparing booleans toTrueand has a very imperative feel to it. A more idiomatic solution would be something like this.This is a simple function chain where
wordssplits up the input into a list of words,map lengthreplaces each word with its length, andmaximumreturns the maximum of those lengths.Although, note that it’s not the exact same as your code, since the
wordsfunction uses slightly different criteria when splitting the input.