Skip to content

Instantly share code, notes, and snippets.

@jutememo
Created February 19, 2011 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jutememo/834817 to your computer and use it in GitHub Desktop.
Save jutememo/834817 to your computer and use it in GitHub Desktop.
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 = do (word, idx) <- s
wordIdx <- if length word < length w
then return (w, idx+1)
else return (word, idx)
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