Created
August 24, 2019 04:31
-
-
Save chakrit/21587ced796cc60400037960d8cd8c9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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