Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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