这是haskell教程的一个例子:
type Bindings = Map.Map String Int
isCountCorrect :: Bindings -> Bool
isCountCorrect bindings = runReader calc_isCountCorrect bindings
calc_isCountCorrect :: Reader Bindings Bool
calc_isCountCorrect = do
count <- asks (lookupVar "count")
bindings <- ask
return (count == (Map.size bindings))
lookupVar :: String -> Bindings -> Int
lookupVar name bindings = fromJust (Map.lookup name bindings)
sampleBindings = Map.fromList [("count", 4), ("1", 1), ("b", 2)]
main = do
putStr $ "Count is correct for bindings " ++ (show sampleBindings) ++ ": "
putStrLn $ show (isCountCorrect sampleBindings)
我创建了函数来获取“2”的值。我不知道如何使它成为任意String的通用。你能帮帮我吗?
get_valueM :: Reader Bindings Int
get_valueM = asks (lookupVar "b") >>= (\value -> ask >>= (\_ -> return value))
get_value :: Bindings -> Int
get_value bindings = runReader get_valueM bindings
答案 0 :(得分:0)
我不确定我完全理解这个问题。为什么不为"b"
添加参数?
get_valueM :: String -> Reader Bindings Int
get_valueM x = asks (lookupVar "b") >>= (\value -> ask >>= (\_ -> return value))
顺便问一下,最后ask
是什么?你不使用它的结果,它没有副作用,所以它看起来可以删除。
get_valueM :: String -> Reader Bindings Int
get_valueM x = asks (lookupVar "b") >>= (\value -> return value)
可以简化为
get_valueM :: String -> Reader Bindings Int
get_valueM x = asks (lookupVar "b") >>= return
可以简化为
get_valueM :: String -> Reader Bindings Int
get_valueM x = asks (lookupVar "b")
最后,让我补充一点,我认为这些部分功能很危险。找不到绑定时,lookupVar
不应该崩溃。不过,这些在玩弄时很方便。