Created
November 7, 2016 21:23
-
-
Save vaibhavsagar/f3039c979c2c52817776aae19138f08a to your computer and use it in GitHub Desktop.
Cute interview question solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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