gpt4 book ai didi

haskell - 莫纳德变形金刚。第一步

转载 作者:行者123 更新时间:2023-12-02 18:48:32 25 4
gpt4 key购买 nike

让我们考虑一下:

type Name   =  String                -- variable names

data Exp = Lit Integer -- expressions
| Var Name
| Plus Exp Exp
| Abs Name Exp
| App Exp Exp
deriving (Show)

data Value = IntVal Integer -- values
| FunVal Env Name Exp
deriving (Show)

type Env = Map.Map Name Value -- mapping from names to values

eval0 :: Env -> Exp -> Value
eval0 env (Var n) = fromJust (Map.lookup n env )

以上为0版本。

现在,让我们考虑一元,1 版本:

type Eval1 a = Identity a
eval1 :: Env -> Exp -> Eval1 Value
eval1 env (Var n) = Map.lookup n env

现在,作者说:

The next is that the Var case does not need a fromJust call anymore: The reason is that Map.lookup is defined to work within any monad by simply calling the monad’s fail function – this fits nicely with our monadic formulation here. (The fail function of the Maybe monad returns Nothing, whereas the fail function in the Identity monad throws an exception, which will lead to different error messages.)

内容来自:http://www.cs.virginia.edu/~wh5a/personal/Transformers.pdf我不清楚。请解释一下为什么引入 monad Eval1 让我们可以不关心 fromJust

编辑:

现在,我尝试编译它,但出现错误,这个错误与我的直觉和怀疑一致。编译器说:

Couldn't match type `Maybe Value' with `Identity Value'
Expected type: Eval1 Value
Actual type: Maybe Value
In the return type of a call of `Map.lookup'
In the expression: Map.lookup n env
In an equation for `eval1': eval1 env (Var n) = Map.lookup n env

那么,谁是对的,作者还是编译器以及如何修复它?

最佳答案

在起草该草案时,Data.Map.lookup 显然可以与任何 monad 配合使用。这不再是事实,但作者确实提供了 updated version本教程的内容。

具体来说,您必须检查生成的 Maybe String 值并显式调用 fail

-- Copied from the link above
eval1 env (Var n) = maybe (fail ("undefined variable: " ++ n)) return $ Map.lookup n env

关于haskell - 莫纳德变形金刚。第一步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36529465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com