다른 재귀 유형 클래스처럼 작동하지만 "상위"클래스만큼 인스턴스가없는 재귀 유형 클래스는 어떻게 작성합니까? 여기 재귀 유형 클래스의 서브 세트에서 유형 클래스 (또는 재귀 유형에서 유형)
은 예입니다data Atom = Atom
data (Formula a) => Negation a = Negation a
class Formula a where
instance Formula Atom where
instance (Formula a) => Formula (Negation a) where
class SubFormula a where
instance SubFormula Atom where
그 코드가 잘 컴파일하지만, 서브 타입 클래스
formulaToSubFormula :: (Formula a, SubFormula b) => a -> b
formulaToSubFormula _ = Atom
중 하나에 슈퍼 타입 클래스의 인스턴스를 변환하는 기능을 추가 할 때 나는 오류를 얻을
test.hs:12:25:
Could not deduce (b ~ Atom)
from the context (Formula a, SubFormula b)
bound by the type signature for
formulaToSubFormula :: (Formula a, SubFormula b) => a -> b
at test.hs:12:1-28
`b' is a rigid type variable bound by
the type signature for
formulaToSubFormula :: (Formula a, SubFormula b) => a -> b
at test.hs:12:1
In the expression: Atom
In an equation for `formulaToSubFormula':
formulaToSubFormula _ = Atom
원래의 의도는 일반적인 유형으로 이것을하는 것이었지만 유형 클래스를 사용하면 문제가 더 친숙하고 일반적으로보다 유연 해 보입니다. 예를 들어
: I 입력 유형에 대한 조작은 일부를 반환하는 형식 수준에 확인하려면 :
data Formula = Atom | Negation Formula | Conjunction Formula Formula
data SubFormula = Atom | Negation SubFormula
편집
내가 달성하기 위해 무엇을하려고 명확히하려면 그 결과로 그 유형의.
확장 예 (명제 논리 아니오 유효한 하스켈 구문)
data Formula = Atom
| Negation Formula
| Disjunction Formula Formula
| Implication Formula Formula
data SimpleFormula = Atom
| Negation SimpleFormula
| Disjunction SimpleFormula SimpleFormula
-- removeImplication is not implemented correctly but shows what I mean
removeImplication :: Formula -> SimpleFormula
removeImplication (Implication a b) = (Negation a) `Disjunction` b
removeImplication a = a
나중 시점에서 I는 논리 곱 표준형의 수식 (NO 유효 하스켈 구문)
data CNF = CNFElem
| Conjunction CNF CNF
data CNFElem = Atom
| Negation Atom
| Disjunction CNFElem CNFElem
를 가질 수있다 따라서이 계층 구조를 나타내는 도구가 필요합니다.
'removeImplication' 계획에서 가장 외적인'Implication' 생성자 만 제거한다는 것에주의하십시오. 'removeImplication (Negation (Implication x y))'는'(Negation (Implication x y))'가됩니다. 간단한 솔루션은'Formula'와'NormalForm'과'toNormalForm' 두 가지 타입을 가지는데, 복잡한 공식을 거치고 시적을 적절한 NormalForm으로 재귀 적으로 변환합니다. 나는 우리가 아직도 당신이 어디로 가고 있는지에 대해 더 알 필요가 있다고 생각합니다. – applicative
@applicative :'removeImplication' 함수는 내가 의미하는 바를 보여주기위한 것입니다. 사실,'NormalForm'은'Formula'의 부분 집합입니다. 그래서이 두 유형을 공유 할 수있는 방법을 찾고 있습니다. –
당신의 더 넓은 목적은 여전히 불투명합니다. 예를 들어, '스티븐 테 틀리 (Stephen tetley)'가 언급 한 경로 중 하나를 택할 가치가 있는지 여부. 데이터 유형 정의, 특히 재귀 적 데이터 유형 정의는 축소 형 언어와 같습니다. 당신은 몇 가지 작은 언어와 그들의 관계를 고려하고 있습니다. 왜 이러한 관계가 유형 * 사이의 함수로 표현되어서는 안 되는가? 'L1'과'L2'가 타입이라면,'L1-> L2'와'L2-> L1' 타입이 그것들 사이의 관계 유형입니다. – applicative