是的,可以在有限的范围内做到这一点。
但首先我们需要
{-# LANGUAGE Rank2Types #-}
让我们定义一下
data M a b = M { name :: Int -> String -> String, eval :: a -> b }
我正在为您的名字添加更多结构,以便我可以获得更好的演出支持。 ;)
然后我们定义一个类:
class Magic m where
magic :: M a b -> m a b
instance Magic M where
magic = id
instance Magic (->) where
magic (M _ f) = f
现在,考虑类型:
type MyFunc a b = forall m. Magic m => m a b
结果类型为magic
或者是(a -> b)
or a M a b
.
所以它可以作为成员使用MyFunc
。现在,这种类型有点令人不满意,因为您无法在其上分派实例,但这确实意味着
inc :: MyFunc Int Int
inc = magic (M (const (showString "inc")) (+1))
test :: Int
test = inc 1
工作得很好。
我们甚至可以用一种相当不错的方式来展示它们。即使我们不能使用 show onMyFunc
,我们可以将其定义为M
.
instance Show (M a b) where
showsPrec d (M s _) = s d
然后我们可以创建一个可以应用的函数M a b
(并且通过扩展任何MyFunc
)得到一个M a b
.
m :: M a b -> M a b
m = id
我们可以定义一个特殊的组合器来显示MyFunc
s:
showM :: MyFunc a b -> String
showM f = show (m f)
然后我们就可以玩了。我们可以定义MyFunc
s.
infixr 9 .#
(.#) :: MyFunc b c -> MyFunc a b -> MyFunc a c
f .# g = magic (M
(\d -> showParen (d > 9) $ showsPrec 10 (m f) .
showString " . " .
showsPrec 9 (m g))
(f . g))
inc2 :: MyFunc Int Int
inc2 = inc .# inc
test2 :: Int
test2 = inc2 1
bar, baz :: String
bar = showM inc
baz = showM inc2
而且因为我给了名称足够的结构,我们甚至可以为更复杂的组合得到正确的括号,而没有不必要的括号。
*Main> showM $ inc2 .# inc
"(inc . inc) . inc"
*Main> showM $ inc .# inc2
"inc . inc . inc"
但请记住,您将无法为MyFunc
,因为它只能是一个type
,而不是一个newtype
。为了定义实例,您必须定义它们M
,然后使用m
转换为该类型,以便隐式调度有一个可以抓住的类型。
由于等级 2 类型,如果您在本地上下文中大量使用这些,您可能还需要打开NoMonoLocalBinds
and/or NoMonomorphismRestriction
.