一副扑克牌,每次出示4张,以四则运算计算它的值,给出结果为24的表达式。请以haskell实现代码。
时间: 2023-02-27 17:58:52 浏览: 95
您可以使用以下Haskell代码来实现24点游戏的表达式:
```haskell
import Data.List (permutations)
data Card = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King
deriving (Show, Eq, Enum)
data Operation = Add | Sub | Mul | Div
deriving (Show, Eq)
eval :: Double -> Double -> Operation -> Double
eval x y Add = x + y
eval x y Sub = x - y
eval x y Mul = x * y
eval x y Div = x / y
valid :: [Double] -> Bool
valid [x] = x == 24
valid (x:y:ys) = any (\op -> valid [eval x y op] ++ ys) [Add, Sub, Mul, Div]
main :: IO ()
main = do
let cards = [Ace .. King]
let nums = map fromIntegral [1 .. 13]
let cardNums = zip cards nums
let cardValues = map (\card -> snd $ head $ filter ((== card) . fst) cardNums)
let expressions = map (\[a, b, c, d] -> [a, b, c, d]) $ permutations nums
let solutions = map (\expression -> (expression, valid $ cardValues expression)) expressions
let validSolutions = filter (\(_, isValid) -> isValid) solutions
print validSolutions
```
该代码使用`permutations`函数从列表中生成所有排列,并使用`valid`函数通过四则运算检查它们是否等于24。最终,该代码会输出所有等于24的表达式。
阅读全文