2011-02-01 32 views
1

我有2問題約2 Haskell函數2 Haskell的問題

  1. flipSymbol ::模型 - >原子 - >模型該功能必須採取模型和原子和翻轉在原子的真值模型。現在我想寫這樣的功能是這樣的:...

    flipSymbol m a = map f m 
        where 
        f (atom, value) = if a == atom then (atom, not value) else (atom, value)

    有沒有更好的方法?

  2. 第二個是一個更復雜的東西,我需要一些幫助,但如果可能的話.. 爲了檢查一個公式的可滿足在我們傳播到原子分配真值的影響,給定模型在一個公式中。假設我們爲其指定值True的原子。以下效果 可以應用到下式:

    • 正文字具有相同的真值,因此,包含它們的任何條款從式除去。這表明這些條款可以得到滿足,因此不再影響公式的可滿足性。
    • 否定字面值爲False,因此從它們所在的任何子句中移除。這表示這些子句仍然不滿足,只能通過其他文字之一才能獲得值的真實。如果將False指定給原子,則正文本現在將是錯誤的,應從其子句中刪除 ,否定文字將變爲true,並將其子句從公式中刪除。例如,在公式(P_Q_R)^(:P_Q_R)^(P_:Q)中,假設我們將真分配給P.然後,包含P的子句,即。 (P _ Q _ R)和(P _:Q)從公式中移除,而:P從它所在的任何子句中移除,即。 (:P _ Q _:R)。這導致公式(Q_:R)。另一方面,如果我們將假賦予P,則我們從公式中去掉(:P _ Q _:R),從它的子句中去掉P,從而得到(Q_R)^(:Q)。
      如果可以將整個公式縮減爲空列表,則整個公式是可以滿足的,因爲在這種情況下,所有條款都滿足了。如果在整個公式中有一個空列表,那麼這意味着一個條款不被滿足,因此公式不能滿足導致這個狀態的任務。
    • assign :: (Atom,Bool) -> Formula -> Formula賦值函數應該採用(Atom,Bool)對和一個公式,並將給定的真值分配給公式中的原子,如上所述。

的代碼(關於這一點我收到的幫助從這裏也可以):

module Algorithm where 

import System.Random 
import Data.Maybe 
import Data.List 

type Atom = String 
type Literal = (Bool,Atom) 
type Clause = [Literal] 
type Formula = [Clause] 
type Model = [(Atom, Bool)] 
type Node = (Formula, ([Atom], Model)) 

-- This function takess a Clause and return the set of Atoms of that Clause. 
atomsClause :: Clause -> [Atom] 
atomsClause = undefined 

-- This function takes a Formula returns the set of Atoms of a Formula 
atoms :: Formula -> [Atom] 
atoms = nub . map snd 

-- This function returns True if the given Literal can be found within 
-- the Clause. 
isLiteral :: Literal -> Clause -> Bool 
isLiteral = isLiteral = any . (==) 

-- this function takes a Model and an Atom and flip the truthvalue of 
-- the atom in the model 
flipSymbol :: Model -> Atom -> Model -- is this ok? 
flipSymbol m a = map f m where 
    f (atom, value) = if a == atom 
     then (atom, not value) 
     else (atom, value) 

assign :: (Atom,Bool) -> Formula -> Formula 
assign = undefined --any advice here? 
+0

請使用4個縮進來格式化您的代碼。 – 2011-02-01 11:17:06

+1

atomsClause = nub。 map snd被定義爲 – TKFALS 2011-02-01 11:17:43

回答

2

一目瞭然,我看不出有任何的方式來提高你的第一個公式,也許你可以使用邏輯功能,而不是一個if-then-else,它的速度更快:

flipSymbol m a = map f m where 
    f (atom, value) = (atom, value /= (a == atom)) 

注意:/=Bool基本上是XOR。

回到最後一個問題: 基本的想法是比較原子,並結合Bool值並且用邏輯運算來獲得結果。基本上,它看起來像這樣:

assign :: (Atom,Bool) -> Formula -> Formula 
assign (a,b) = map . (map f) where 
    f (x,b) = (x,(x==a)&&b)