隐含的参数和功能

nik*_*scp 9 parameters haskell implicit ghc wordnet

考虑Haskell(GHC)中的隐式参数,我遇到了问题.我有一个函数f,它假定隐含参数x,并希望通过将f应用于g来将其封装在上下文中

f :: (?x :: Int) => Int -> Int
f n = n + ?x

g :: (Int -> Int) -> (Int -> Int)
g t = let ?x = 5 in t
Run Code Online (Sandbox Code Playgroud)

但是当我试图评估时

g f 10
Run Code Online (Sandbox Code Playgroud)

我得到一个x没有绑定的错误,例如:

Unbound implicit parameter (?x::Int)
  arising from a use of `f'
In the first argument of `g', namely `f'
In the second argument of `($)', namely `g f 10'
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我,我做错了什么?

(我试图让Haskell的WordNet接口工作 - http://www.umiacs.umd.edu/~hal/HWordNet/ - 它以上述方式使用隐式参数,并且我不断收到错误当我尝试编译它时上面一个)

小智 6

第一个参数g必须是类型,((?x::Int) => Int -> Int)以澄清?x应该传递给f.这可能是启用Rank2Types(或RankNTypes).不幸的是,GHC无法推断出这种类型.

{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE Rank2Types #-}

f :: (?x::Int) => Int -> Int
f n = n + ?x

g :: ((?x::Int) => Int -> Int) -> (Int -> Int)
g f = let ?x = 5 in f`
Run Code Online (Sandbox Code Playgroud)

现在g f 10有效.


jek*_*kor 5

这里的问题是它?x没有受到引用的限制.你和我可以看到?x它将被绑定g,但编译器不能.一个(令人困惑的)解决方案是改变

g f 10
Run Code Online (Sandbox Code Playgroud)

g (let ?x = 5 in f) 10
Run Code Online (Sandbox Code Playgroud)