Skip to content

Instantly share code, notes, and snippets.

@jutememo
Created February 12, 2011 18:07
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/823947 to your computer and use it in GitHub Desktop.
Save jutememo/823947 to your computer and use it in GitHub Desktop.
import Text.Regex
type State s a = s -> (a, s)
comb :: State s a -> (a -> State s b) -> State s b
comb m k = \s -> let (x1, s') = m s in k x1 s'
comb_ :: State s a -> State s b -> State s b
comb_ m n = m `comb` \_ -> n
ret :: a -> State s a
ret x = \s -> (x, s)
get :: State s s
get = \s -> (s, s)
put :: s -> State s ()
put x = \_ -> ((), x)
execState :: State s a -> s -> s
execState s s0 = snd $ s s0
longestWord' :: [String] -> State (String, Int) ()
longestWord' [] = ret ()
longestWord' (x:xs) = get `comb` \x1@(word, idx) ->
put (x, idx+1) `comb_`
longestWord' xs `comb_`
get `comb` \x2@(word', idx') ->
if length word < length word' then put x2 else put x1
longestWord (x:xs) = (execState $ longestWord' xs) (x, 0)
main = print $ longestWord $ splitRegex (mkRegex " ") "The quick brown fox"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment