sha*_*ang 11 haskell types function-calls
是否可以使用您自己的数据类型模拟具有GHC扩展名的函数?我想做的是例如
(假想的语法)
data MyFunc = MyFunc String (Int->Int)
instance (Int->Int) MyFunc where
($) (MyFunc _ f) i = f i
inc = MyFunc "increment" (1+)
test = inc 1Run Code Online (Sandbox Code Playgroud)
即带有一些元信息的数据,可以进行模式匹配,但仍可以像常规函数一样调用.现在,我知道我可以定义自己的中缀运算符$$和调用inc $$ 1,但是能够使用常规函数调用语法在嵌入式DSL中非常有用.
Edw*_*ETT 18
是的,它可以在有限的范围内完成.
但首先我们需要
{-# LANGUAGE Rank2Types #-}
Run Code Online (Sandbox Code Playgroud)
我们来定义
data M a b = M { name :: Int -> String -> String, eval :: a -> b }
Run Code Online (Sandbox Code Playgroud)
我正在为你的名字添加更多结构,所以我可以获得更好的节目支持.;)
然后我们定义一个类:
class Magic m where
magic :: M a b -> m a b
instance Magic M where
magic = id
instance Magic (->) where
magic (M _ f) = f
Run Code Online (Sandbox Code Playgroud)
现在,考虑类型:
type MyFunc a b = forall m. Magic m => m a b
Run Code Online (Sandbox Code Playgroud)
结果类型magic是(a -> b)或者a M a b.
所以它可以作为成员使用MyFunc.现在,这种类型有点令人不满意,因为你无法在其上调度实例,但它确实意味着
inc :: MyFunc Int Int
inc = magic (M (const (showString "inc")) (+1))
test :: Int
test = inc 1
Run Code Online (Sandbox Code Playgroud)
工作得很好.
我们甚至可以用一种相当不错的方式来展示它们.即使我们不能使用show MyFunc,我们也可以为它定义M.
instance Show (M a b) where
showsPrec d (M s _) = s d
Run Code Online (Sandbox Code Playgroud)
然后我们可以创建一个我们可以应用的函数M a b(以及任何扩展名MyFunc)来获取M a b.
m :: M a b -> M a b
m = id
Run Code Online (Sandbox Code Playgroud)
我们可以定义一个特殊的组合来显示MyFuncs:
showM :: MyFunc a b -> String
showM f = show (m f)
Run Code Online (Sandbox Code Playgroud)
然后我们就可以玩了.我们可以定义MyFuncs的组合.
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
Run Code Online (Sandbox Code Playgroud)
因为我为这些名字提供了足够的结构,所以我们甚至可以为更复杂的作品获得正确的括号,而不需要不必要的括号.
*Main> showM $ inc2 .# inc
"(inc . inc) . inc"
*Main> showM $ inc .# inc2
"inc . inc . inc"
Run Code Online (Sandbox Code Playgroud)
但请记住,您将无法定义任何实例MyFunc,因为它只能是a type,而不是a newtype.为了定义实例,您必须在其上定义它们M,然后使用m转换为该类型,以便隐式分派具有要抓取的类型.
由于等级2类型,如果您在本地环境中大量使用这些,您可能还需要打开NoMonoLocalBinds和/或NoMonomorphismRestriction.