Ремонт принтеров, сканнеров, факсов и остальной офисной техники

назад Оглавление вперед


"Kibi said: I am a boy." The other adds: "Kibi is a girl. Kibi lied." Solve for the sex of Kibi and the sex of each parent.

We will need some additional predicates specific to this puzzle, and to define the universe of allowed variables values:

Code available in example24.hs

-if a male says something, it must be true said :: Var -> Predicate -> Predicate

said v p = (v "Is" "male") "implies" p

-- if a male says two things, they must be true

-- if a female says two things, one must be true and one must be false

saidBoth :: Var -> Predicate -> Predicate -> Predicate

saidBoth v pl p2 = And ((v "Is" "male") "implies" (pl "And" p2))

((v "Is" "female") "implies" (pl "orElse" p2))

-lying is saying something is true when it isnt or saying something isnt true when it is

lied :: Var -> Predicate -> Predicate

lied v p = ((v "said" p) "And" (Not p)) "orElse" ((v "said" (Not p)) "And" p)

-- Test consistency over all allowed settings of the variable. tryAllValues :: Var -> NDS ()

tryAllValues var = do (setVar var "male") "mplus" (setVar var "female")

c <- isConsistent True guard c

All that remains to be done is to define the puzzle in the predicate language and get a solution that satisfies all of the predicates:

Code available in example24.hs

-- Define the problem, try all of the variable assignments and print a


main :: IO ()

main = do let variables = []

constraints = [ Not (Equal "parentl" "parent2"),

"parentl" "said" ("child" "said" ("child" "Is"


saidBoth "parent2" ("child" "Is" "female")

("child" "lied" ("child"

"Is" "male")) ]

problem= PS variables constraints

print $ ("getSolution" problem) $ do tryAllValues "parentl"

tryAllValues "parent2" tryAllValues "child" getFinalVars

ФП 02005-03 01

Копиоова Формат

св а: =з

Each call to tryAllValues will fork the solution space, assigning the named variable to be "male" in one fork and "female" in the other. The forks which produce inconsistent variable assignments are eliminated (using the guard function). The call to getFinalVars applies guard again to eliminate inconsistent variable assignments and returns the remaining assignments as the value of the computation.

3.7. Managing the transformer stack

As the number of monads combined together increases, it becomes increasingly important to manage the stack of monad transformers well.

3.7.1.Selecting the correct order

Once you have decided on the monad features you need, you must choose the correct order in which to apply the monad transformers to achieve the results you want. For instance you may know that you want a combined monad that is an instance of MonadError and MonadState, but should you apply StateT to the Error monad or ErrorT to the State monad?

The decision depends on the exact semantics you want for your combined monad. Applying StateT to the Error monad gives a state transformer function of type s -> Error e (a,s). Applying ErrorT to the State monad gives a state transformer function of type s -> (Error e a,s). Which order to choose depends on the role of errors in your computation. If an error means no state could be produced, you would apply StateT to Error. If an error means no value could be produced, but the state remains valid, then you would apply ErrorT to State.

Choosing the correct order requires understanding the transformation carried out by each monad transformer, and how that transformation affects the semantics of the combined monad.

3.7.2.An example with multiple transformers

The following example demonstrates the use of multiple monad transformers. The code uses the StateT monad transformer along with the List monad to produce a combined monad for doing stateful nondeterministic computations. In this case, however, we have added the WriterT monad transformer to perform logging during the computation. The problem we will apply this monad to is the famous N-queens problem: to place N queens on a chess board so that no queen can attack another.

The first decision is in what order to apply the monad transformers. StateTs (WriterTw []) yields a type like: s -> [((a,s),w)]. WriterTw (StateTs []) yields a type like: s -> [((a,w),s)]. In this case, there is little difference between the two orders, so we will choose the second arbitrarily.

ФП 02005-03 01

Лист 67

Копиоова Формат

Our combined monad is an instance of both MonadState and MonadWriter, so we can freely mix use of get, put, and tell in our monadic computations.

Code available in example25.hs

-- this is the type of our problem description

data NQueensProblem = NQP {board::Board,

ranks::[Rank], files::[File], asc::[Diagonal], desc::[Diagonal]}

-initial state = empty board, all ranks, files, and diagonals free initialState = let fileA = map (\r->Pos A r) [l..8]

rank8 = map (\f->Pos f 8) [A .. H] rankl = map (\f->Pos f l) [A .. H] asc = map Ascending (nub (fileA ++ rankl)) desc = map Descending (nub (fileA ++ rank8)) in NQP (Board []) [l..8] [A .. H] asc desc

-- this is our combined monad type for this problem

type NDS a = WriterT [String] (StateT NQueensProblem []) a

-Get the first solution to the problem, by evaluating the solver computation with

-- an initial problem state and then returning the first solution in the result list,

-- or Nothing if there was no solution.

getSolution :: NDS a -> NQueensProblem -> Maybe (a,[String]) getSolution c i = listToMaybe (evalStateT (runWriterT c) i)

-- add a Queen to the board in a specific position

addQueen :: Position -> NDS ()

addQueen p = do (Board b) <- gets board

rs <- gets ranks

fs <- gets files

as <- gets asc

ds <- gets desc

let b = (Piece Black Queen, p):b

rs = delete (rank p) rs

fs = delete (file p) fs

(a,d) = getDiags p

as = delete a as

ds = delete d ds tell ["Added Queen at " ++ (show p)] put (NQP (Board b) rs fs as ds)

-- test if a position is in the set of allowed diagonals inDiags :: Position -> NDS Bool inDiags p = do let (a,d) = getDiags p as <- gets asc

ФП 02005-03 01

Лист 68

№ докум.

Копиоова Фоомат

[стр.Начало] [стр.1] [стр.2] [стр.3] [стр.4] [стр.5] [стр.6] [стр.7] [стр.8] [стр.9] [стр.10] [стр.11] [стр.12] [стр.13] [стр.14] [стр.15] [стр.16] [стр.17] [стр.18] [стр.19] [стр.20] [стр.21] [стр.22] [стр.23] [стр.24] [стр.25]