#!/usr/bin/envstack{- stack
--resolver lts-12.0
--install-ghc
script
--ghc-options -Werror
--ghc-options -Wall
--package echo
--package random
--
-}--------------------------------------------------------------------------------{-# LANGUAGE Safe #-}--------------------------------------------------------------------------------moduleMain(main)where--------------------------------------------------------------------------------importData.List(sort)importData.Maybe(fromMaybe)importSystem.IO.Echo(withoutInputEcho)importSystem.Random(newStdGen,randomRs)importText.Read(readMaybe)---------------------------------------------------------------------------------- The type `Box` should be moved to a common `library` used by both Bob and Ali-- and it shouldn't expose the constructor `Box`. That way, we ensure that the-- type `Box` can't implement an instance for `Show`.---- Note: As this mimic a `physical` representation of `Boxes`, we aren't going-- into further details on how to tranfer these `Boxes` over the wire.newtypeBox=Box{box::(Integer,Ordering)}typeBoxes=[Box]typeLower=IntegertypeUpper=Integerrands::Int->Lower->Upper->IO[Integer]randsnlu=taken.randomRs(l,u)<$>newStdGenaction01::Integer->IOBoxesaction01x=-- Bob gives his labeled box to `UPS` at Location A. Afterwards, the driver-- takes further 10 boxes and randomly label them in the range (lower = x / 5,-- upper = x * 5), based on the amout `x` of Bobs fortune stated on his-- box. They drive the 11 boxes to Ali at Location B.map(Box.flip(,)undefined).sort.(x:)<$>rands10luwherel=x`div`5u=x*5action02::Integer->Boxes->Boxesaction02x=-- Ali, at Location B, put stickers (EQ,LT and GT) on all boxes based on her-- fortune compared to the values on each box. When this is done, the `UPS`-- driver, bring them all back to Bob at Location A.map$Box.aux.boxwhereaux=\(i,_)->(i,comparexi)action03::Integer->Boxes->Orderingaction03x=-- Since Bob only knows the value of his Box, he can only request that to the-- driver of the `UPS` van. If he began to guess randomly and fails, the-- driver might get suspicious and will abort any delivery.snd.box.head.filter((==x).fst.box)--------------------------------------------------------------------------------main::IO()main=putStr"Location A | Bob gives his box: ">>=\_->help<$>withoutInputEcho(getLine)>>=\bob->putStrLn"********">>=\_->putStr"Location B | Ali label the boxes: ">>=\_->help<$>withoutInputEcho(getLine)>>=\ali->putStrLn"********">>=\_->action03bob.action02ali<$>action01bob>>=putStrLn.(info++).showwhereinfo="Location A | Bob sees that Ali's fortune is: "help=fromMaybe0.readMaybe
Code Output:
user@personal:~/../ymp$ ./YaosMillionairesProblem.hs
Location A | Bob gives his box: ******** # Bobs fortune is 42
Location B | Ali label the boxes: ******** # Alis fortune is 84
Location A | Bob sees that Ali's fortune is: GT