🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of martinsvalin

martinsvalin's solution

to Matching Brackets in the Elm Track

Published at Jun 11 2020 · 0 comments
Instructions
Test suite
Solution

Given a string containing brackets [], braces {}, parentheses (), or any combination thereof, verify that any and all pairs are matched and nested correctly.

Elm Installation

Refer to the Installing Elm page for information about installing elm.

Writing the Code

The code you have to write is located inside the src/ directory of the exercise. Elm automatically installs packages dependencies the first time you run the tests so we can start by running the tests from the exercise directory with:

$ elm-test

To automatically run tests again when you save changes:

$ elm-test --watch

As you work your way through the tests suite in the file tests/Tests.elm, be sure to remove the skip <| calls from each test until you get them all passing!

Source

Ginna Baker

Submitting Incomplete Solutions

It is possible to submit an incomplete solution so you can see how others have completed the exercise.

Tests.elm

module Tests exposing (tests)

import Expect
import MatchingBrackets exposing (isPaired)
import String
import Test exposing (..)


tests : Test
tests =
    describe "MatchingBrackets"
        [ test "paired square brackets" <|
            \_ ->
                Expect.equal True (isPaired "[]")
        , skip <|
            test "empty string" <|
                \_ ->
                    Expect.equal True (isPaired "")
        , skip <|
            test "unpaired brackets" <|
                \_ ->
                    Expect.equal False (isPaired "[[")
        , skip <|
            test "wrong ordered brackets" <|
                \_ ->
                    Expect.equal False (isPaired "}{")
        , skip <|
            test "wrong closing bracket" <|
                \_ ->
                    Expect.equal False (isPaired "{]")
        , skip <|
            test "paired with whitespace" <|
                \_ ->
                    Expect.equal True (isPaired "{ }")
        , skip <|
            test "partially paired brackets" <|
                \_ ->
                    Expect.equal False (isPaired "{[])")
        , skip <|
            test "simple nested brackets" <|
                \_ ->
                    Expect.equal True (isPaired "{[]}")
        , skip <|
            test "seceral paired brackets" <|
                \_ ->
                    Expect.equal True (isPaired "{}[]")
        , skip <|
            test "paired and nested brackets" <|
                \_ ->
                    Expect.equal True (isPaired "([{}({}[])])")
        , skip <|
            test "unopened closing brackets" <|
                \_ ->
                    Expect.equal False (isPaired "{[)][]}")
        , skip <|
            test "unpaired and nested brackets" <|
                \_ ->
                    Expect.equal False (isPaired "([{])")
        , skip <|
            test "paired and wrong nested brackets" <|
                \_ ->
                    Expect.equal False (isPaired "[({]})")
        , skip <|
            test "math expression" <|
                \_ ->
                    Expect.equal True (isPaired "(((185 + 223.85) * 15) - 543)/2")
        , skip <|
            test "complex latex expression" <|
                \_ ->
                    Expect.equal True (isPaired "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)")
        ]
module MatchingBrackets exposing (isPaired)

import Parser exposing ((|.), Parser, Step(..), chompIf, chompWhile, end, loop, map, oneOf, run, succeed, symbol)


isPaired : String -> Bool
isPaired input =
    case run parser input of
        Ok _ ->
            True

        Err _ ->
            False


parser : Parser ()
parser =
    loop end inner


inner : Parser a -> Parser (Step (Parser a) ())
inner stop =
    oneOf
        [ stop |> map (\_ -> Done ())
        , parenthesis |> map (\_ -> Loop stop)
        , brackets |> map (\_ -> Loop stop)
        , curlies |> map (\_ -> Loop stop)
        , other |> map (\_ -> Loop stop)
        ]


parenthesis : Parser ()
parenthesis =
    matchingSymbols "(" ")"


brackets : Parser ()
brackets =
    matchingSymbols "[" "]"


curlies : Parser ()
curlies =
    matchingSymbols "{" "}"


matchingSymbols : String -> String -> Parser ()
matchingSymbols open close =
    succeed ()
        |. symbol open
        |. loop (symbol close) inner


other : Parser ()
other =
    let
        regular char =
            not <| List.member char (String.toList "([{}])")
    in
    chompIf regular |. chompWhile regular

Community comments

Find this solution interesting? Ask the author a question to learn more.

martinsvalin's Reflection

Another day, another parser. Using Parser for this actually worked out well in the end, I think. I could use `Result.Extra.isOk` in `isPaired` and maybe tighten up the parsers a little bit, but overall, I think it reads well.

Input should be a repetition of different types of matched brackets, or non-bracket junk, so we have an outer loop until the end of the string.

Matched brackets, in turn, have the same rules for their content, except they stop at their matched closing bracket, not the end of the string.

When I realized I could carry a parser as my loop state was my galaxy brain moment. =)