0

I have a list which is comprised of a list of strings, declared as:

type alias Model =
    { board : List (List String)
    }

init : Model
init =
    { board = 
        [ ["", "", ""]
        , ["", "", ""]
        , ["", "", ""]
        ]
    }

In my update function, I am attempting to access an inner element of the lists via

(getAt col (getAt row model.board))

I get the following error when I try to compile it though. How do I convert from Maybe List to Just List or simply List?

The 2nd argument to `getAt` is not what I expect:

65|                         (getAt col (getAt row model.board))
                                        ^^^^^^^^^^^^^^^^^^^^^
This `getAt` call produces:

    Maybe (List String.String)

But `getAt` needs the 2nd argument to be:

    List a
Dull Bananas
  • 892
  • 7
  • 29
CambodianCoder
  • 467
  • 4
  • 14
  • 1
    That's the thing, Elm forces you to handle the case where there's not element and `getAt` returns nothing. You can either use a `case .. of` or `Maybe.withDefault` and there's probably other ways as well but all of them will require you to specify what should happen if there's no element, on way or another. – ivarni Mar 26 '20 at 06:48
  • 2
    Does this answer your question? [Right way to forcibly convert Maybe a to a in Elm, failing clearly for Nothings](https://stackoverflow.com/questions/28699800/right-way-to-forcibly-convert-maybe-a-to-a-in-elm-failing-clearly-for-nothings) – ivarni Mar 26 '20 at 06:49

3 Answers3

1

First to answer your question: use case .. of or Maybe.withDefault.

But it looks like you want to do something, for what a list is not the right solution.

If you have a list, and you know it is never empty, use something like a List.Nonempty

If you know the numbers of entries in each list, use something like a vector

For your 2D Board, I would suggest creating your own (opaque) custom type. Or maybe this matrix will be helpful.

Fabian S.
  • 909
  • 6
  • 20
1

You can try:

model.board
|> getAt row
|> Maybe.withDefault []
|> getAt col

OR even better

model.board
|> getAt row
|> Maybe.andThen (getAt col)

(see https://package.elm-lang.org/packages/elm/core/latest/Maybe for more info)

romainsalles
  • 2,051
  • 14
  • 17
1

Also you have Maybe.Extra.values which does exactly what you want

Kutyel
  • 8,575
  • 3
  • 30
  • 61