CambodianCoder
CambodianCoder

Reputation: 487

How to convert Maybe (List) to Just List in Elm?

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

Upvotes: 0

Views: 1308

Answers (3)

Kutyel
Kutyel

Reputation: 9084

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

Upvotes: 1

romainsalles
romainsalles

Reputation: 2143

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)

Upvotes: 1

Fabian S.
Fabian S.

Reputation: 977

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.

Upvotes: 1

Related Questions