From 99f72644724ba7907d9d18ac71fe7804eb475c22 Mon Sep 17 00:00:00 2001 From: kazbekovruslan Date: Thu, 30 May 2024 01:25:43 +0300 Subject: [PATCH] fix bracket sequence checker --- Homework4/BracketSequence/BracketSequence.fs | 68 +++++++++++--------- 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/Homework4/BracketSequence/BracketSequence.fs b/Homework4/BracketSequence/BracketSequence.fs index ef0ff01..0b97ddd 100644 --- a/Homework4/BracketSequence/BracketSequence.fs +++ b/Homework4/BracketSequence/BracketSequence.fs @@ -1,32 +1,42 @@ module BracketSequence +let braces = [ ('(', ')'); ('[', ']'); ('{', '}') ] + +// without another declaring braces in function I have nullReferenceException +let isOpeningBracket x = + let braces = [ ('(', ')'); ('[', ']'); ('{', '}') ] + braces |> List.exists (fun (opening, _) -> opening = x) + +let isClosingBracket x = + let braces = [ ('(', ')'); ('[', ']'); ('{', '}') ] + braces |> List.exists (fun (_, closing) -> closing = x) + +let isBracePair x y = + let braces = [ ('(', ')'); ('[', ']'); ('{', '}') ] + List.contains (x, y) braces + let isBracketSequenceCorrect (str: string) = - let bracketPairs = [ ('(', ')'); ('[', ']'); ('{', '}') ] - let stack = System.Collections.Generic.Stack() - - str - |> Seq.forall (fun c -> - match c with - | '(' - | '[' - | '{' -> - stack.Push(c) - true - | ')' - | ']' - | '}' -> - if stack.Count = 0 then - false - else - let expected = - bracketPairs - |> List.tryFind (fun pair -> fst pair = stack.Peek()) - |> Option.map snd - - match expected with - | Some expectedChar when expectedChar = c -> - stack.Pop() - true - | _ -> false - | _ -> true) - && stack.Count = 0 + let rec helper (stack, seq) = + match seq with + | [] -> List.isEmpty stack + | first :: seqTail when isOpeningBracket first -> helper ((first :: stack), seqTail) + | first :: seqTail when isClosingBracket first -> + match stack with + | [] -> false + | top :: stackTail -> + if isBracePair top first then + helper (stackTail, seqTail) + else + false + | _ :: seqTail -> helper (stack, seqTail) + + helper ([], Seq.toList str) + + + +let str1 = "[a]" + +let isBalanced1 = isBracketSequenceCorrect str1 // true + + +printfn "%A" $"{isBalanced1}"