给Elm中可能包含Int类型的记录赋Int值



我是Elm的新手,所以如果我的问题是非常基本的,请原谅。

请考虑以下代码:

-- 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 }

两种赋值方式给我几乎相同的错误:

# 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.

这两个错误表明编译器将24视为数字,而不是将其视为Int

我的问题是,为什么会发生这种情况,我如何能够分配值给我的记录正确与这种类型?谢谢。

好吧,我自己也算出来了。

根据Elm的官方文档,这是正常工作的代码:

-- 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 }

Just成功了。

详细的解释是Maybe类型接受NothingJust为其类型的值。

最新更新