I am trying to find the shortest and longest word in a given string. If the entered string is “house tap mobile telephone” then the longest word should be telephone and shortest will be tap. I have already written the following functions. How do i find the index of the strings and find the shortest and longest word out of it?
---------Converting string into a list of strings and finding length of each word--------
stringConvert :: String -> [Int]
stringConvert x = map (length) (words x)
----------Find the longest word-----------
findLongestWord :: String -> Int
findLongestWord x = maximum(stringConvert x)
----------Find the shortest word-----------
findShortestWord :: String -> Int
findShortestWord x = minimum(stringConvert x)
Since you are looking for a certain word, the signatures of your functions should be
The
stringConvertfunction you have implemented has the right idea, but it is a bit problematic because the result doesn’t have the information which word is associated with which length. It might be better to separate splitting the string into a word list from the length calculation, and there is a handy function calledcomparingthat actually removes the need for thestringConvertfunction altogether.maximumByis similar tomaximumbut it takes as the first parameter a function that should be used to compare two items.comparingis a higher-order function that can be used to convert a function of typea -> b(wherebis some type that can be compared, i.e.Ord b => a -> bif you are already familiar with type constraints) into a comparison function between twoa‘s (i.e. a function of typea -> a -> Ordering).The shortest word can be found in a similar manner.