|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Меню:
Главная
Форум
Литература: Программирование и ремонт Импульсные блоки питания Неисправности и замена Радиоэлектронная аппаратура Микросхема в ТА Рубрикатор ТА Кабельные линии Обмотки и изоляция Радиоаппаратура Гибкие диски часть 2 часть 3 часть 4 часть 5 Ремонт компьютера часть 2 Аналитика: Монтаж Справочник Электроника Мощные высокочастотные транзисторы 200 микросхем Полупроводники ч.1 Часть 2 Алгоритмические проблемы 500 микросхем 500 микросхем Сортировка и поиск Монады Передача сигнала Электроника Прием сигнала Телевидиние Проектирование Эвм Оптимизация Автомобильная электроника Поляковтрансиверы Форт Тензодатчик Силовые полевые транзисторы Распределение частот Резисторные и термопарные Оберон Открытые системы шифрования Удк |
[20] "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 solution. main :: IO () main = do let variables = [] constraints = [ Not (Equal "parentl" "parent2"), "parentl" "said" ("child" "said" ("child" "Is" "male")), 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
св а: =з 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.
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
|
Среды: Smalltalk80 MicroCap Local bus Bios Pci 12С ML Микроконтроллеры: Atmel Intel Holtek AVR MSP430 Microchip Книги: Емкостный датчик 500 схем для радиолюбителей часть 2 (4) Структура компьютерных программ Автоматическая коммутация Кондиционирование и вентиляция Ошибки при монтаже Схемы звуковоспроизведения Дроссели для питания Блоки питания Детекторы перемещения Теория электропривода Адаптивное управление Измерение параметров Печатная плата pcad pcb Физика цвета Управлении софтверными проектами Математический аппарат Битовые строки Микроконтроллер nios Команды управления выполнением программы Перехода от ahdl к vhdl Холодный спай Усилители hi-fi Электронные часы Сердечники из распылённого железа Анализ алгоритмов 8-разрядные КМОП Классификация МПК История Устройства автоматики Системы и сети Частотность Справочник микросхем Вторичного электропитания Типы видеомониторов Радиобиблиотека Электронные системы Бесконтекстный язык Управление техническими системами Монтаж печатных плат Работа с коммуникациями Создание библиотечного компонента Нейрокомпьютерная техника Parser Пи-регулятор ч.1 ПИ-регулятор ч.2 Обработка списков Интегральные схемы Шина ISAВ Шина PCI Прикладная криптография Нетематическое: Взрывной автогидролиз Нечеткая логика Бытовые установки (укр) Автоматизация проектирования Сбор и защита Дискретная математика Kb радиостанция Энергетика Ретро: Прием в автомобиле Управление шаговым двигателем Магнитная запись Ремонт микроволновки Дискретные системы часть 2 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||