模式匹配Elm中具体类型中的多态类型
我使用的是elm form:,我需要将多态类型模式匹配为具体类型,但是我遇到了下一个错误:模式匹配Elm中具体类型中的多态类型,elm,Elm,我使用的是elm form:,我需要将多态类型模式匹配为具体类型,但是我遇到了下一个错误: The pattern matches things of type: TranslationId But the values it will actually be trying to match are: e Hint: Your type annotation uses type variable `e` which means any type of value can
The pattern matches things of type:
TranslationId
But the values it will actually be trying to match are:
e
Hint: Your type annotation uses type variable `e` which means any type of value
can flow through. Your code is saying it CANNOT be anything though! Maybe change
your type annotation to be more specific? Maybe the code has a problem? More at:
<https://github.com/elm-lang/elm-compiler/blob/0.18.0/hints/type-annotations.md>
ErrorValue类型:
TranslationId类型:
我想出了一个解决方案,但它看起来很奇怪,我不确定它是否正确:
正如@reactormonk所说,您没有在类型定义中处理类型变量。elm表单通过该类型变量在自定义错误中提供了灵活性,如果您想使用自定义错误,则必须提供该类型变量(如果您不这样做,则可以在整个代码中使用该变量,而不会出现任何问题) 特别是
ErrorValue
有一个类型变量e
,您需要指定它:它在不使用CustomError构造函数的代码中不重要,但在translateError
中重要,因为您正在尝试对CustomError进行模式匹配。看起来您想要的类型是TranslationId
所以您想要
translateError : ErrorValue TranslationId -> String
translateError error =
case error of
InvalidEmail ->
translate English ErrInvalidEmail
Empty ->
translate English ErrEmpty
CustomError PasswordNotMatch ->
translate English PasswordNotMatch
x ->
toString x
这是因为您没有指定
e
在translateError:ErrorValue e->String
中是什么,所以它对它一无所知。也许传入e->String
函数?我这样做了,然后从调用它,然后我更改了类型签名:errorFor:FieldState TranslationId String->Html msg
,然后我从中得到一个错误,最后我卡住了。我试图让我的答案更完整一点,但建议是sameYes,我很感激你花时间来检查这个。然而,也许我解释得不够充分,根据你们的建议,我得到了这个,它从elm表单包调用了一个函数getFieldAsString
,正如你们所看到的,它需要一种形式:FieldState e String
,但我传递的是:FieldState TranslationId String
,这就产生了错误。我可以分叉包并更改getFieldAsString
的类型签名,但我想也许有更好的解决方案,感谢所有的帮助。您得到的错误是在您的代码中,而不是在elm形式中。您的错误是,是因为您试图在类型CustomError e
上进行模式匹配,但未指定类型e
type ErrorValue e
= Empty
| InvalidString
| InvalidEmail
| InvalidUrl
| InvalidFormat
| InvalidInt
| InvalidFloat
| InvalidBool
| InvalidDate
| SmallerIntThan Int
| GreaterIntThan Int
| SmallerFloatThan Float
| GreaterFloatThan Float
| ShorterStringThan Int
| LongerStringThan Int
| NotIncludedIn
| CustomError e
type TranslationId
= ErrInvalidEmail
| PasswordNotMatch
| ErrEmpty
translateError : ErrorValue e -> String
translateError error =
case error of
InvalidEmail ->
translate English ErrInvalidEmail
Empty ->
translate English ErrEmpty
CustomError e ->
case (toString e) of
"PasswordNotMatch" ->
translate English PasswordNotMatch
x ->
toString x
x ->
toString x
translateError : ErrorValue TranslationId -> String
translateError error =
case error of
InvalidEmail ->
translate English ErrInvalidEmail
Empty ->
translate English ErrEmpty
CustomError PasswordNotMatch ->
translate English PasswordNotMatch
x ->
toString x