是否可以从其中一个子功能中的功能定义引用类型? (有关更多详细信息,请参见下面代码中的注释)
module TypesAndSubFunctions where
class DingBat k where
foo :: DingBat k => k -> String
foo kv = "foo"
where
-- how can I define bar so that the type 'k2' is the same
-- as k from foo? Or is this not possible?
--
-- The following causes an error, because k2 isn't the same type
-- as foo's k. But I can't seem to find a way to reference foo's k
-- without specifying it as an arg (as I do in bar2). Is this just
-- the way haskell is?
--
-- I would think there should be a simple way to reference k from
-- foo with the type definition of bar, but I can't see how.
-- bar :: DingBat k2 => k2 -> String
-- bar kv2 = ding2 kv kv2
-- To restate the problem, I would like the same functionality for
-- bar as bar2, below, but without having to specify the first arg
bar2 :: DingBat k => k -> k -> String
bar2 kv kv2 = ding2 kv kv2
ding2 :: DingBat k => k -> k -> String
ding2 = undefined
答案 0 :(得分:2)
这应该可以完成工作。要重用k
,您需要打开一个非常通用的扩展名。
{-# LANGUAGE ScopedTypeVariables #-}
foo :: forall k . DingBat k => k -> String
foo kv = "foo"
where
bar :: k -> String
bar kv2 = ding2 kv kv2