daily pastebin goal
11%
SHARE
TWEET

Untitled

a guest Jan 18th, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Codewars.Kata.Braces where
  2.  
  3. import Control.Monad ((>=>))
  4. import Control.Applicative ((<|>))
  5.  
  6. newtype Validator = Validator { check :: String -> Maybe String }
  7.  
  8. validChar :: Char -> Validator
  9. validChar c = Validator  v
  10.     where
  11.     v (c' : rest)  | c' == c = Just rest
  12.     v _            = Nothing
  13.    
  14. fail :: Validator
  15. fail = Validator $ const Nothing
  16.  
  17. pass :: Validator
  18. pass = Validator Just
  19.    
  20. andThen :: Validator -> Validator -> Validator
  21. v1 `andThen` v2 = Validator $ check v1 >=> check v2
  22.  
  23. orElse :: Validator -> Validator -> Validator
  24. v1 `orElse` v2 = Validator $ \s -> check v1 s <|> check v2 s
  25.  
  26. some :: Validator -> Validator
  27. some v = v `andThen` many v
  28.  
  29. many :: Validator -> Validator
  30. many v = some v `orElse` pass
  31.  
  32. wrapped :: Char -> Char -> Validator -> Validator
  33. wrapped l r v = validChar l `andThen` v `andThen` validChar r
  34.  
  35. wrappedRound :: Validator -> Validator
  36. wrappedRound = wrapped '(' ')'
  37.  
  38. wrappedSquare :: Validator -> Validator
  39. wrappedSquare = wrapped '[' ']'
  40.  
  41. wrappedCurly :: Validator -> Validator
  42. wrappedCurly = wrapped '{' '}'
  43.  
  44. balancedOnce :: Validator
  45. balancedOnce =
  46.        wrappedRound pass
  47.        `orElse` wrappedSquare pass
  48.        `orElse` wrappedCurly pass
  49.        `orElse` wrappedRound more
  50.        `orElse` wrappedSquare more
  51.        `orElse` wrappedCurly more
  52.    where more = some balancedOnce
  53.  
  54. validBraces :: String -> Bool
  55. validBraces = maybe False (== []) . check (many balancedOnce)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top