我有很多方法在他們的定義中都有樣板代碼,請看上面的示例。在Haskell函數中匹配模式
replace:: Term -> Term -> Formula -> Formula
replace x y (Not f) = Not $ replace x y f
replace x y (And f g) = And (replace x y f) (replace x y g)
replace x y (Or f g) = Or (replace x y f) (replace x y g)
replace x y (Biimp f g) = Biimp (replace x y f) (replace x y g)
replace x y (Imp f g) = Imp (replace x y f) (replace x y g)
replace x y (Forall z f) = Forall z (replace x y f)
replace x y (Exists z f) = Exists z (replace x y f)
replace x y (Pred idx ts) = Pred idx (replace_ x y ts)
如您所見,replace
函數的定義遵循一種模式。我想有功能相同的行爲,簡化了他的定義,可能使用一些模式匹配,可能與通配符_
或X
在爭論,是這樣的:
replace x y (X f g) = X (replace x y f) (replace x y g)
爲了避免以下定義:
replace x y (And f g) = And (replace x y f) (replace x y g)
replace x y (Or f g) = Or (replace x y f) (replace x y g)
replace x y (Biimp f g) = Biimp (replace x y f) (replace x y g)
replace x y (Imp f g) = Imp (replace x y f) (replace x y g)
有什麼方法嗎?忘記功能的目的,它可以是任何東西。
也許'DeriveFunctor'或做它一個明確的實例?那麼上面的結果可能是'替換x y = fmap(\ z - >如果x == z然後y其他x)''。當然,這意味着'公式'將會有'* - > *',但這聽起來很合理。 「Formula Bool」將是一個布爾公式。 – Alec
你可以使'Formula'成爲['Compos']的一個實例(https://hackage.haskell.org/package/uniplate-1.6.12/docs/Data-Generics-Compos.html),這會有幫助嗎? – Cactus