我有一个描述OrderItem
的记录类型:
type alias Product {- = some record type -}
type alias Quantity = Int
type alias OrderItem = {
product: Product
, quantity: Quantity
, fillable: Maybe Bool
}
执行产品查找的功能:
productByCode : String -> Maybe Product
和构建orderItem的函数:
orderItem : String -> Quantity -> Result OrderItem
orderItem productCode quantity =
let
product = productByCode productCode
in
case product of
Just p -> Ok { product = p, quantity = quantity, fillable = Nothing }
Nothing -> Err ("Unknown product code: " ++ productCode)
但是这个函数会导致编译错误:
-- TYPE MISMATCH ---------------------------------------------- src/elm/Main.elm The type annotation for `orderItem` does not match its definition. 65│ orderItem : String -> Quantity -> Result OrderItem ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The type annotation is saying: String -> Quantity -> Result OrderItem But I am inferring that the definition has this type: String -> Quantity -> Result String { fillable : Maybe a, product : Product, quantity : Quantity }
错误告诉我编译器没有匹配OrderItem类型,因为Nothing
不匹配Maybe Bool
- 但肯定Nothing
在这里是有效值吗?文档似乎允许以这种方式使用它。
我哪里出错?
答案 0 :(得分:2)
类型注释应为:
orderItem : String -> Quantity -> Result String OrderItem
这告诉编译器该值的类型为Ok OrderItem
或Err String