Haskell语法:解析输入错误 [英] Haskell Syntax: Parse Error On Input
问题描述
app
的函数。我想要这个函数做的是接受这些参数 epp(App e1 e2)
。第一步是递归评估 e1
( epp e1
)并检查输出是否为错误。如果不是,则评估 e2
,然后调用另一个函数 eppVals
来评估 e1
和 e2
,我定义为 v1
和 v2 。解决方案在你的hpaste中你有一个函数 appVals ,在上面的问题中它已被重命名为 eppVals
。这是无益的。
让我们来看看一些类型:
-
epp :: Exp - >错误Val
-
appVals :: Val - > Val - >错误Val
错误消息无法匹配预期类型 Val
与实际类型错误Val
试图告诉您,第一个参数 appVals $ Val
(请参阅 appVals
的类型签名) 但作为第一个参数提供的值的实际类型是 v1
,定义为 epp e1
code>,它的类型为 Error Val
(请参阅 epp
的类型签名)。
Val
和错误Val
不是同一类型。这是你的问题。
如何解决它?您需要一些方法来处理与其余计算分开的错误情况。如果您为错误
实施了 Applicative
或 Monad
类>类型,这几乎肯定是他们做的。
编辑:您不包括错误
,但我想它看起来像这样:
data Error a = S a |错误字符串
为它实现几个类(您需要导入Control.Applicative
):
pre $ instance Functor Error其中
fmap f(S x )= S(fx)
fmap _(Error s)=错误s
实例应用错误其中
pure = S
错误s * _ =错误s
_< *>错误s =错误s
S f * S x = S(fx)
现在您可以重写
epp(App e1 e2)= eppVals< $> epp e1 * epp e2
As part of a mini-haskell compiler that I'm writing, I have a function named app
. What I want this function to do is take in these arguments epp (App e1 e2)
. The first step would be to evaluate e1
recursively (epp e1
) and check if the output would be an error. If not then evaluate e2
and then call another function eppVals
to evaluate the outputs of the calls on e1
and e2
which I defined as v1
and v2
respectively.
解决方案 In your hpaste you have a function appVals
which has been renamed to eppVals
in your question above. This is unhelpful.
Let's look at some types:
epp :: Exp -> Error Val
appVals :: Val -> Val -> Error Val
The error message Couldn't match expected type Val
with actual type Error Val
is trying to tell you that the first parameter to appVals
is expected to have type Val
(see type signature for appVals
) but the actual type of the value you've provided as the first parameter is v1
, defined as epp e1
, which has type Error Val
(see type signature for epp
).
Val
and Error Val
are not the same type. That's your problem.
How to fix it? You need some way of handling the error cases separately from the rest of the computation. If you have implemented the Applicative
or Monad
classes for your Error
type, this is almost certainly what they do.
Edit: You don't include the definition of your Error
, but I expect it looks like this:
data Error a = S a | Error String
Implement a couple of classes for it (you'll need to import Control.Applicative
):
instance Functor Error where
fmap f (S x) = S (f x)
fmap _ (Error s) = Error s
instance Applicative Error where
pure = S
Error s <*> _ = Error s
_ <*> Error s = Error s
S f <*> S x = S (f x)
Now you can rewrite
epp (App e1 e2) = eppVals <$> epp e1 <*> epp e2
这篇关于Haskell语法:解析输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!