Skip to content

Instantly share code, notes, and snippets.

@vaibhavsagar
Created November 7, 2016 21:23
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 vaibhavsagar/f3039c979c2c52817776aae19138f08a to your computer and use it in GitHub Desktop.
Save vaibhavsagar/f3039c979c2c52817776aae19138f08a to your computer and use it in GitHub Desktop.
Cute interview question solution
import qualified Data.Map.Strict as Map
import Data.List (inits, tails, any)
match "" "" _ = True
match "" _ _ = False
match _ "" _ = False
match expr text matches = let
possibilities = zip (tail $ inits text) (tail $ tails text)
pattern = head expr
expr' = tail expr
possibilities' = if (Map.member pattern matches)
then filter (\(m, _) -> (matches Map.! pattern) == m) possibilities
else possibilities
branches = map (step expr' pattern matches) possibilities'
in any id branches
where
step exp pat matches (mat, rest) = let
matches' = Map.insert pat mat matches
in match exp rest matches'
match' expr text = match expr text Map.empty
main = do
print $ match' "abba" "catdogdogcat"
print $ match' "abab" "catdogcatdog"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment