Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Control.Monad.State
type Word = String -- 最長の文字列
type Idx = Int -- 最長の文字列のインデックス
type Index = Int -- ループで使うインデックス
longestWord' :: [String] -> State Index (Word, Idx)
longestWord' (x:xs) = foldl f (return (x, 0)) xs
where
f :: State Index (Word, Idx) -> String -> State Index (Word, Idx)
f s w = s >>= \(word, idx) ->
(if length word < length w
then return (w, idx+1)
else return (word, idx)) >>= \wordIdx ->
State $ \i -> (wordIdx, i+1)
longestWord xs = let (wordIdx, _) = runState (longestWord' xs) 0 in wordIdx
main = print $ longestWord $ words "The quick brown fox"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment