Prologサンプルについてはわかりませんが、Haskellで次のように定義します。
{-# LANGUAGE MultiParamTypeClasses, EmptyDataDecls, FlexibleInstances,
FlexibleContexts, UndecidableInstances, TypeFamilies, ScopedTypeVariables #-}
data Z
data S a
type One = S Z
type Two = S One
type Three = S Two
type Four = S Three
class Plus x y r
instance (r ~ a) => Plus Z a r
instance (Plus a b p, r ~ S p) => Plus (S a) b r
p1 = undefined :: (Plus Two Three r) => r
class Mult x y r
instance (r ~ Z) => Mult Z a r
instance (Mult a b m, Plus m b r) => Mult (S a) b r
m1 = undefined :: (Mult Two Four r) => r
class Fac x r
instance (r ~ One) => Fac Z r
instance (Fac n r1, Mult (S n) r1 r) => Fac (S n) r
f1 = undefined :: (Fac Three r) => r
class Pow x y r
instance (r ~ One) => Pow x Z r
instance (r ~ Z) => Pow Z y r
instance (Pow x y z, Mult z x r) => Pow x (S y) r
pw1 = undefined :: (Pow Two Four r) => r
-- Handy output
class (Num n) => ToNum a n where
toNum :: a -> n
instance (Num n) => ToNum Z n where
toNum _ = 0
instance (ToNum a n) => ToNum (S a) n where
toNum _ = 1 + toNum (undefined :: a)
main = print $ (toNum p1, toNum m1, toNum f1, toNum pw1)
アップデート:
danportinが以下のコメントで指摘しているように、TypeFamiliesの「レイジーパターン」(インスタンスコンテキスト)はここでは必要ありません(彼の初期コードは短く、はるかにクリーンです)。
ただし、この質問のコンテキストで考えることができるこのパターンの1つのアプリケーションは、次のとおりです。ブール論理を型レベルの演算に追加するとします。
data HTrue
data HFalse
-- Will not compile
class And x y r | x y -> r
instance And HTrue HTrue HTrue
instance And a b HFalse -- we do not what to enumerate all the combination here - they all HFalse
ただし、「機能依存性の競合」のため、これはコンパイルされません。そして、私たちはまだ、fundepsなしでこの重複するケースを表現できるように見えます:
class And x y r
instance (r ~ HTrue) => And HTrue HTrue r
instance (r ~ HFalse) => And a b r
b1 = undefined :: And HTrue HTrue r => r -- HTrue
b2 = undefined :: And HTrue HFalse r => r -- HFalse
これは間違いなく最も良い方法ではありません(IncoherentInstancesが必要です)。したがって、誰かが別の、より「トラウマ的でない」アプローチを提案できるかもしれません。