0

Im new to Elm , previously I was doing React, Redux , ES6 Need help optimizing the below counter example using Array rather than List. Getting error Type mismatch When I tried to use Array Set/Get methods.

import Html exposing (beginnerProgram, div, button, text, p, Html, span)
import Html.Events exposing (onClick)
import Array

main =
  beginnerProgram { model = [0,7], view = view, update = update }


view model =
  div []
    [ div [] [ button [ onClick AddCounter ] [ text "Add Counter" ] ]
      , div [] (List.indexedMap  (\index data -> (viewCounter index data)) model)
    ]
viewCounter: Int -> Int -> Html Msg
viewCounter index data =
    div [] [
    p [] [text ("Counter " ++ toString index )]
    , button [ onClick (Decrement index) ] [ text "-" ]
    , span [] [ text (toString data) ]
    , button [ onClick (Increment index) ] [ text "+" ]
    ]


type Msg = 
  AddCounter 
  | Increment Int
  | Decrement Int

incrementSelectedIndex index selectedIndex data = 
  if index == selectedIndex then data + 1
  else data

decrementSelectedIndex index selectedIndex data = 
  if index == selectedIndex then data + 1
  else data


update msg model =
  case msg of
    AddCounter ->
      List.append model [0] 

    Increment selectedIndex ->
      (List.indexedMap  (\index data -> 
        (incrementSelectedIndex index selectedIndex data)) model)  

    Decrement selectedIndex ->
      (List.indexedMap  (\index data -> 
        (decrementSelectedIndex index selectedIndex data)) model) 
Sabha B
  • 2,079
  • 3
  • 28
  • 40

1 Answers1

3

Array.get returns a Maybe a since the requested index may not be found. This may be different than other languages with which you have experience, which tend to throw exceptions when an index is out of bounds.

In Elm, the Maybe type has two possible values: Nothing, and Just a where a is the actual value you care about.

You can use a case statement to differentiate between the two options. Here is an example of what your Increment case can look like using Array's get and set functions:

Increment selectedIndex ->
  case Array.get selectedIndex model of
    Just val -> Array.set selectedIndex (val + 1) model
    Nothing -> model

Notice that if we ask for a nonexistent index, we would get Nothing and just return the original array rather than crashing the program.

Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
  • Finally I understood Maybe effortlessly , Many Thanks Chad. – Sabha B Mar 16 '17 at 00:12
  • Is there a recommended way to use either Array or List for such use case , please clarify w.r.t to performance (memory & speed). . – Sabha B Mar 16 '17 at 02:18
  • 1
    There's a bit more info along with links [in this answer](http://stackoverflow.com/questions/37707577/array-vs-list-in-elm) – Chad Gilbert Mar 16 '17 at 03:04