‘m a student, just starting working with Haskell and have problems with part of code. I does not understand how this code works. Can anyone explain my how it worked?
check :: String -> Bool
check = check' [] where
check' [] [] = True
check' _ [] = False
check' x ('(':xs) = check' ('(':x) xs
check' ('(':x) (')':xs) = check' x xs
check' _ (')':xs) = False
check' x (_ :xs) = check' x xs
This first parameter of
check'function serves as a stack to count the opened brackets. Every time it encounters an opening bracket, it appends it to the stack and proceeds with the rest of the input line:Then, when it encounters a closing bracket, it pops an opening bracket and proceeds:
But if there is a closing bracket and no opening ones left in the stack, it fails:
Also, if the line is over, and unclosed brackets remain, fail:
By default, the stack is empty. The rest are the obvious boundary cases.