Assigning Int Values to a Record Containing Maybe Int Type in Elm

Viewed 36

I'm very new to Elm so please excuse me if my question is very basic.

Please consider the following code:

-- Defining an alias type containing the type Maybe Int
type alias User = { name : String, age : Maybe Int }

-- Trying to assign values by the record constructor
newUser = User "Kyxey" 24

-- or by =
newUser : User
newUser = { name = "Kyxey", age = 24 }

Both ways of value assignments give me almost the same error of:

# Either this for the record constructor
-- TYPE MISMATCH --------------------------------------------------------- /repl

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

3| newUser = User "Kyxey" 24
                          ^^
This argument is a number of type:

    number

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

    Maybe Int

Hint: I always figure out the argument types from left to right. If an argument
is acceptable, I assume it is “correct” and move on. So the problem may actually
be in one of the previous arguments!

Hint: Only Int and Float values work as numbers.

# or this for =
-- TYPE MISMATCH --------------------------------------------------------- /repl

Something is off with the body of the `newUser` definition:

4| newUser = { name = "Kyxey", age = 24 }
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The body is a record of type:

    { age : number, name : String }

But the type annotation on `newUser` says it should be:

    User

Hint: Only Int and Float values work as numbers.

Both errors indicate that the compiler is treating 24 as a number and not as an Int which it is.

My question is that why is this happening and how am I able to assign values to my record properly with this type? Thanks.

1 Answers

Ok I just figured it out myself.

According to the official Elm's docs, this is the code that works fine:

-- Defining an alias type containing the type Maybe Int
type alias User = { name : String, age : Maybe Int }

-- Trying to assign values by the record constructor
newUser = User "Kyxey" (Just 24)

-- or by =
newUser : User
newUser = { name = "Kyxey", age = Just 24 }

That Just does the trick.

A detailed explanation would be that Maybe types either accept Nothing or Just a value of their type.

Related