说我有一个功能:
f :: Int -> (Rational, Integer)
f b = ((toRational b)+1,(toInteger b)+1)
Run Code Online (Sandbox Code Playgroud)
我想像这样抽象出(+1):
f :: Int -> (Rational, Integer)
f b = (h (toRational b)
,h (toInteger b))
where h = (+1)
Run Code Online (Sandbox Code Playgroud)
这显然不会起作用,但如果我指定类型签名,它将起作用:
f :: Int -> (Rational, Integer)
f b = (h (toRational b)
,h (toInteger b))
where h :: Num a => a -> a
h = (+1)
Run Code Online (Sandbox Code Playgroud)
假设我现在想通过传递h作为参数来进一步抽象函数:
f :: Num a => Int -> (a -> a) -> (Rational, Integer)
f b g = (h …Run Code Online (Sandbox Code Playgroud) polymorphism haskell referential-transparency higher-rank-types
说我有以下(错误的)代码.
data A a b where
APure :: (A a b)
AApply :: A (A b c) c
test :: (A a b) -> a -> b
test (APure) a = a
test AApply a = undefined
Run Code Online (Sandbox Code Playgroud)
然后GHC会给我这个错误:
Couldn't match type `b' with `A b1 b'
`b' is a rigid type variable bound by
the type signature for test :: A a b -> a -> b
Inaccessible code in
a pattern with constructor
AApply :: forall c b. A …Run Code Online (Sandbox Code Playgroud) 说我有以下GADT:
data Stage a b where
Comb :: Stage a b -> Stage b c -> Stage a c
FMap :: (a -> b) -> Stage a b
Run Code Online (Sandbox Code Playgroud)
我现在想要一个像这样工作的函数:
run (a `Comb` b) = (a,b)
run (FMap f) = (FMap f,FMap id)
Run Code Online (Sandbox Code Playgroud)
我该如何构建这样的函数?
我尝试了不同的绑定类型的方法,但没有成功.是否存在我缺少的扩展,可以实现更广泛的类型绑定?
这是错误消息:
Couldn't match type `t' with `(Stage t1 b, Stage b t2)'
`t' is a rigid type variable bound by
the inferred type of run :: Stage t1 t2 -> t at <interactive>:11:5
In the expression: …Run Code Online (Sandbox Code Playgroud)