syntax - Why doesn't the case expression work in this Elm code? -


i wrote elm code snippet draw square , change square color between red , black every time when mouse clicked.

however case structure in changecolor function doesn't work expected, while changecolor implemented if structure work.

what should figure out what's going wrong? thank you.

import color exposing (red, black, blue, color) import signal exposing ((<~)) import graphics.element exposing (element, show) import graphics.collage exposing (collage, square, filled, form) import mouse import window  main : signal element main =    scene <~ (signal.foldp changecolor black mouse.clicks)  scene : color -> element scene color =    collage 600 600 [ filled_square color ]  changecolor : () -> color -> color changecolor _ color =   case color of     black -> red     red -> black  --changecolor _ color = --  if | color == black -> red --     | color == red -> black  filled_square : color -> form filled_square color = square 100 |> filled color 

pattern variables (the short answer)

lowercase names in case patterns considered variables, never constants. case statement match color against pattern variable black, succeeds, , binds name black value of color inside case branch (-> red).

in case multi-way if have in comments appropriate way distinguish cases.

using case expressions

case expressions used distinguish cases in union types. example explicitly model program states union type so:

import color exposing (red, black, blue, color) import signal exposing ((<~)) import graphics.element exposing (element, show) import graphics.collage exposing (collage, square, filled, form) import mouse import window  type model = red | black  main : signal element main =    scene <~ (signal.foldp changecolor black mouse.clicks)  scene : model -> element scene model =    collage 600 600 [ filled_square (tocolor model) ]  tocolor : model -> color tocolor model =   case model of     black -> black     red -> red  changecolor : () -> model -> model changecolor _ model =   case model of     black -> red     red -> black  filled_square : color -> form filled_square color = square 100 |> filled color 

the reason doing have finite, enumerable states program in easy find place. if use colours, know sure looking through entire program. case expression exhaustive, handles states program can in. whereas multi-way if on colours, knows if colours possible have in program, once grows larger toy-example-size. if don't match possible colours, run runtime crash of application. (this 1 of few possible ways happen in elm)


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -