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

eliotbo's solution

to Matching Brackets in the Elm Track

Published at Jan 22 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 (..)
import Set exposing (..)

import Browser
import Html as Ht exposing (..)
import Html.Events exposing (..)
import Html.Attributes as HA exposing (..)
import Bool.Extra exposing (toString)

--run parser on string
--eat anything other than parens with |.
--parse parens with |=
--build up a stack of closing paren
--if a closing paren matches the head of the stack, removing it from stack, otherwise, fail
--succeed when the string and the stack are both empty
--fail if string is empty but not the stack


isPaired : String -> Bool
isPaired input = Ok "" == run (Parser.loop "" parseParens) input

--parseParens:stack -> Parser (Step paren stack)
parseParens : String -> Parser (Step String String)
parseParens stack = 
    oneOf 
        [ succeed (\paren -> Loop (appendOrRemoveParen paren stack) )
            |. notParen
            |= (getChompedString <| chompIf isParen)
            |. notParen
        , succeed ()
            |> Parser.map (\_ -> Done stack)
        ]

--either add new paren to stack or remove head of stack
--single character paren -> list of parens -> new list of parens
appendOrRemoveParen : String -> String -> String
appendOrRemoveParen x ys = 
    case String.uncons ys of
        Nothing -> x
        Just (z,zs) -> 
            let 
                addToStack = x ++ ys
                checkMatch q = if z == q then zs else addToStack
            in  case x of
                    "]" -> checkMatch '['
                    "}" -> checkMatch '{' 
                    ")" -> checkMatch '(' 
                    other  -> addToStack


isParen : Char -> Bool
isParen x = 
  Set.member x <| Set.fromList <| String.toList "[](){}"

notParen : Parser ()
notParen = 
  Parser.chompWhile (\x -> not <| isParen x)




main =
  Browser.element
    { init = init
    , update = update
    , subscriptions = subscriptions
    , view = view
    }


type alias Model = { shuffles : Int } 


init : () -> (Model, Cmd Msg)
init _ =
  ( {shuffles = 0} 
  , Cmd.none
  )

type Msg
  = Roll


update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
  
    Roll ->
      ( model
      , Cmd.none
      )


subscriptions : Model -> Sub Msg
subscriptions model =
  Sub.none


view : Model -> Html Msg
view model =
      div [] [Ht.text (Bool.Extra.toString <| isPaired "({[a]})")]

Community comments

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

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?