Skip to content

Instantly share code, notes, and snippets.

@chakrit
Created Aug 24, 2019
Embed
What would you like to do?
module Main exposing (..)
import Browser
import Html exposing (div, input, p, span, strong, text)
import Html.Attributes exposing (value)
import Html.Events exposing (onInput)
type alias Model =
String
type Msg
= Input String
type Balance
= Balanced
| Stagger ( Int, Int, Int ) -- ( [ { respectively
| Unbalanced
balance : ( Int, Int, Int ) -> Balance
balance ( n1, n2, n3 ) =
if n1 > 0 || n2 > 0 || n3 > 0 then
Stagger ( n1, n2, n3 )
else if n1 < 0 || n2 < 0 || n3 < 0 then
Unbalanced
else
-- 0,0,0
Balanced
delta : Char -> ( Int, Int, Int )
delta c =
case c of
'(' ->
( 1, 0, 0 )
'[' ->
( 0, 1, 0 )
'{' ->
( 0, 0, 1 )
')' ->
( -1, 0, 0 )
']' ->
( 0, -1, 0 )
'}' ->
( 0, 0, -1 )
_ ->
-- skip invalid char?
( 0, 0, 0 )
add : Char -> Balance -> Balance
add c b =
let
( d1, d2, d3 ) =
delta c
in
case b of
Unbalanced ->
Unbalanced
Balanced ->
balance ( d1, d2, d3 )
Stagger ( n1, n2, n3 ) ->
balance ( n1 + d1, n2 + d2, n3 + d3 )
check s =
List.foldl add Balanced (String.toList s) == Balanced
init =
""
update msg model =
case msg of
Input s ->
s
view model =
div []
[ p [] [ input [ onInput Input, value model ] [] ]
, p []
[ if check model then
strong [] [ text "BALANCED" ]
else
span [] [ text "nope." ]
]
]
main =
Browser.sandbox
{ init = init
, view = view
, update = update
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment