根据this excellent series中的术语,我们将(1 + x^2 - 3x)^3
表达为Term Expr
,其中数据类型如下:
data Expr a =
Var
| Const Int
| Plus a a
| Mul a a
| Pow a Int
deriving (Functor, Show, Eq)
data Term f = In { out :: f (Term f) }
是否存在适合执行符号区分的递归方案?我觉得它几乎是专注于Term Expr
的Futumorphism,即futu deriveFutu
以获得适当的函数deriveFutu
:
data CoAttr f a
= Automatic a
| Manual (f (CoAttr f a))
futu :: Functor f => (a -> f (CoAttr f a)) -> a -> Term f
futu f = In <<< fmap worker <<< f where
worker (Automatic a) = futu f a
worker (Manual g) = In (fmap worker g)
这看起来很不错,除了下划线变量是Term
而不是CoAttr
s:
deriveFutu :: Term Expr -> Expr (CoAttr Expr (Term Expr))
deriveFutu (In (Var)) = (Const 1)
deriveFutu (In (Const _)) = (Const 0)
deriveFutu (In (Plus x y)) = (Plus (Automatic x) (Automatic y))
deriveFutu (In (Mul x y)) = (Plus (Manual (Mul (Automatic x) (Manual _y)))
(Manual (Mul (Manual _x) (Automatic y)))
)
deriveFutu (In (Pow x c)) = (Mul (Manual (Const c)) (Manual (Mul (Manual (Pow _x (c-1))) (Automatic x))))
没有递归方案的版本如下所示:
derive :: Term Expr -> Term Expr
derive (In (Var)) = In (Const 1)
derive (In (Const _)) = In (Const 0)
derive (In (Plus x y)) = In (Plus (derive x) (derive y))
derive (In (Mul x y)) = In (Plus (In (Mul (derive x) y)) (In (Mul x (derive y))))
derive (In (Pow x c)) = In (Mul (In (Const c)) (In (Mul (In (Pow x (c-1))) (derive x))))
作为这个问题的扩展,是否有一个递归方案来区分和消除&#34;空&#34; Expr
Plus (Const 0) x
,例如A[:-1] = A[1:]
A[-1] = value
因差异而产生 - 一次性传递数据?
答案 0 :(得分:5)
查看产品的差异规则:
(u v)' = u' v + v' u
区分产品需要了解什么?您需要知道子项的衍生物(u'
,v'
)及其值(u
,v
)。
这正是 paramorphism 为您提供的。
para
:: Functor f
=> (f (b, Term f) -> b)
-> Term f -> b
para g (In a) = g $ (para g &&& id) <$> a
derivePara :: Term Expr -> Term Expr
derivePara = para $ In . \case
Var -> Const 1
Const _ -> Const 0
Plus x y -> Plus (fst x) (fst y)
Mul x y -> Plus
(In $ Mul (fst x) (snd y))
(In $ Mul (snd x) (fst y))
Pow x c -> Mul
(In (Const c))
(In (Mul
(In (Pow (snd x) (c-1)))
(fst x)))
在paramorphism中,fst
使您可以访问子项的派生词,而snd
则为您提供术语本身。
作为这个问题的扩展,是否存在一种递归方案,用于区分和消除由于区分而产生的
Plus (Const 0)
x的“空”Exprs - 一次通过数据?
是的,它仍然是一种异形。最简单的方法是使用智能构造函数,例如
plus :: Term Expr -> Term Expr -> Expr (Term Expr)
plus (In (Const 0)) (In x) = x
plus (In x) (In (Const 0)) = x
plus x y = Plus x y
并在定义代数时使用它们。你也许可以将它表达为某种类型的para-cata融合。