编辑:已解决。 我是未能在源文件中启用语言扩展名的未软件,无法在GHCI中启用语言扩展。解决方案是 :set FlexibleContexts 在GHCI。


我最近发现,在Haskell中的课程中,该类型的声明是Horn条款。所以我从 序言的艺术, ,第3章,进入Haskell。例如:

fac(0,s(0)).
fac(s(N),F) :- fac(N,X), mult(s(N),X,F).

class Fac x y | x -> y
instance Fac Z (S Z)
instance (Fac n x, Mult (S n) x f) => Fac (S n) f

pow(s(X),0,0) :- nat(X).
pow(0,s(X),s(0)) :- nat(X).
pow(s(N),X,Y) :- pow(N,X,Z), mult(Z,X,Y).

class Pow x y z | x y -> z
instance (N n) => Pow (S n) Z Z
instance (N n) => Pow Z (S n) (S Z)
instance (Pow n x z, Mult z x y) => Pow (S n) x y

在prolog中,在证明中(逻辑)变量实例化值。但是,我不明白如何在Haskell中实例化类型变量。也就是说,我不明白Haskell等于Prolog Query是什么

?-f(X1,X2,...,Xn)

是。我认为

:t undefined :: (f x1 x2 ... xn) => xi

会导致Haskell实例化 xi, ,但这给了一个 Non type-variable argument in the constraint 错误,即使 FlexibleContexts 已启用。

有帮助吗?

解决方案

对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在下面的评论中指出的那样,这里不需要“懒惰模式”(例如上下文)(他的初始代码更短并且更干净)。

但是,在这个问题的背景下,我可以想到的一种模式的一种应用是:说我们想将布尔逻辑添加到我们的类型级别算术中:

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

但这不会由于“功能依赖性冲突”而汇编。在我看来,我们仍然可以在没有资金的情况下表达这个重叠的案件:

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

这绝对不是最好的方法(它需要不一致的方法)。因此,也许有人可以提出另一种“创伤性”的方法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top