gpt4 book ai didi

haskell - 在haskell中实现统一算法

转载 作者:行者123 更新时间:2023-12-01 21:43:58 28 4
gpt4 key购买 nike

我正在尝试使用指定的算法实现统一函数

unify α α = idSubst
unify α β = update (α, β) idSubst
unify α (τ1 ⊗ τ2) =
if α ∈ vars(τ1 ⊗ τ2) then
error ”Occurs check failure”
else
update (α, τ1 ⊗ τ2) idSubst
unify (τ1 ⊗ τ2) α = unify α (τ1 ⊗ τ2)
unify (τ1 ⊗1 τ2) (τ3 ⊗2 τ4) = if ⊗1 == ⊗2 then
(subst s2) . s1
else
error ”not unifiable.”
where s1 = unify τ1 τ3
s2 = unify (subst s1 τ2) (subst s1 τ4)

其中 ⊗ 是类型构造函数 {→, ×} 之一。

但是我不明白如何在 haskell 中实现这个。我该怎么办呢?

import Data.List
import Data.Char

data Term = Var String | Abs (String,Term) | Ap Term Term | Pair Term Term | Fst Term | Snd Term
deriving (Eq,Show)

data Op = Arrow | Product deriving (Eq)


data Type = TVar String | BinType Op Type Type
deriving (Eq)

instance Show Type where
show (TVar x) = x
show (BinType Arrow t1 t2) = "(" ++ show t1 ++ " -> " ++ show t2 ++ ")"
show (BinType Product t1 t2) = "(" ++ show t1 ++ " X " ++ show t2 ++ ")"

type Substitution = String -> Type

idSubst :: Substitution
idSubst x = TVar x

update :: (String, Type) -> Substitution -> Substitution
update (x,y) f = (\z -> if z == x then y else f z)


-- vars collects all the variables occuring in a type expression
vars :: Type -> [String]
vars ty = nub (vars' ty)
where vars' (TVar x) = [x]
vars' (BinType op t1 t2) = vars' t1 ++ vars' t2

subst :: Substitution -> Type -> Type
subst s (TVar x) = s x
subst s (BinType op t1 t2) = BinType op (subst s t1) (subst s t2)

unify :: Type -> Type -> Substitution
unify (TVar x) (TVar y) = update (x, TVar y) idSubst

最佳答案

unify :: Type -> Type -> Substitution
unify (TVar x) (TVar y) = update (x, TVar y) idSubst

这是一个好的开始!

现在您只需要处理其他情况:

以下是表示第一个的方式:

unify (TVar x) (TVar y) | x == y = idSubst

您可以类似地使用模式匹配将您的 Type 分解为适当的构造函数和防护来处理特定情况。

Haskell 有一个 error::String -> a 函数,其工作方式与上面的伪代码相同,并且 if/then/else 语法是相同的,所以你几乎在那里!

关于haskell - 在haskell中实现统一算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7641282/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com