- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我用 Haskell 编写了一个简单的井字游戏程序。它在命令行上运行,具有单人和两人模式,并在与它对战时实现极小极大算法。
我习惯于用面向对象语言编写正确的代码,但 Haskell 对我来说是新的。这段代码工作得相当好,但似乎很难阅读(即使对我来说也是如此!)。关于如何使这段代码更加...Haskelian 有什么建议吗?
import Data.List
import Data.Char
import Data.Maybe
import Control.Monad
data Square = A | B | C | D | E | F | G | H | I | X | O deriving (Read, Eq, Ord)
instance Show Square where
show A = "a"
show B = "b"
show C = "c"
show D = "d"
show E = "e"
show F = "f"
show G = "g"
show H = "h"
show I = "i"
show X = "X"
show O = "O"
type Row = [Square]
type Board = [Row]
data Player = PX | PO deriving (Read, Eq)
instance Show Player where
show PX = "Player X"
show PO = "Player O"
data Result = XWin | Tie | OWin deriving (Read, Show, Eq, Ord)
main :: IO ()
main = do
putStrLn "Let's play some tic tac toe!!!"
putStrLn "Yeeeaaaaaahh!!!"
gameSelect
gameSelect :: IO ()
gameSelect = do
putStrLn "Who gonna play, one playa or two??? (Enter 1 or 2)"
gameMode <- getLine
case gameMode of "1" -> onePlayerMode
"2" -> twoPlayerMode
gameMode -> gameSelect
where onePlayerMode = do
putStrLn "One playa"
putStrLn "Cool! Get ready to play...AGAINST MY INVINCIBLE TIC TAC TOE AI!!!!! HAHAHAHA!!!"
gameLoop 1 emptyBoard PX
twoPlayerMode = do
putStrLn "Two players"
gameLoop 2 emptyBoard PX
emptyBoard = [[A,B,C],[D,E,F],[G,H,I]]
gameLoop :: Int -> Board -> Player -> IO ()
gameLoop noOfPlayers board player = do
case detectWin board of Just XWin -> endgame board XWin
Just OWin -> endgame board OWin
Just Tie -> endgame board Tie
Nothing -> if noOfPlayers == 1
then if player == PX
then enterMove 1 board player
else enterBestMove board PO
else enterMove 2 board player
enterMove :: Int -> Board -> Player -> IO ()
enterMove noOfPlayers board player = do
displayBoard board
if noOfPlayers == 1
then do putStrLn ("Make your move. (A-I)")
else do putStrLn (show player ++ ", it's your turn. (A-I)")
move <- getLine
print move
if not $ move `elem` ["a","b","c","d","e","f","g","h","i"]
then do
putStrLn $ move ++ " is not a move, doofus"
gameLoop noOfPlayers board player
else if (read (map toUpper move) :: Square) `elem` [ sq | sq <- concat board]
then do
gameLoop noOfPlayers (newBoard (read (map toUpper move) :: Square) player board) (if player == PX then PO else PX)
else do
putStrLn "That square is already occupied"
gameLoop noOfPlayers board player
enterBestMove :: Board -> Player -> IO ()
enterBestMove board player = gameLoop 1 (newBoard bestmove player board) PX
where bestmove = fst $ findBestMove PO board
findBestMove :: Player -> Board -> (Square, Result)
findBestMove player board
| player == PO = findMax results
| player == PX = findMin results
where findMin = foldl1 (\ acc x -> if snd x < snd acc then x else acc)
findMax = foldl1 (\ acc x -> if snd x > snd acc then x else acc)
results = [ (sq, getResult b) | (sq, b) <- boards player board ]
getResult b = if detectWin b == Nothing
then snd (findBestMove (if player == PX then PO else PX) b)
else fromJust $ detectWin b
boards :: Player -> Board -> [(Square, Board)]
boards player board = [(sq, newBoard sq player board) | sq <- concat board, sq /= X, sq /=O]
displayBoard :: Board -> IO ()
displayBoard board = do
mapM_ print board
newBoard :: Square -> Player -> Board -> Board
newBoard move player board = [ [if sq == move then mark else sq | sq <- row] | row <- board]
where mark = if player == PX then X else O
detectWin :: Board -> (Maybe Result)
detectWin board
| [X,X,X] `elem` board ++ transpose board = Just XWin
| [X,X,X] `elem` [diagonal1 board, diagonal2 board] = Just XWin
| [O,O,O] `elem` board ++ transpose board = Just OWin
| [O,O,O] `elem` [diagonal1 board, diagonal2 board] = Just OWin
| [X,X,X,X,X,O,O,O,O] == (sort $ concat board) = Just Tie
| otherwise = Nothing
where
diagonal1 :: Board -> [Square]
diagonal1 bs = bs!!0!!0 : bs!!1!!1 : bs!!2!!2 : []
diagonal2 :: Board -> [Square]
diagonal2 bs = bs!!0!!2 : bs!!1!!1 : bs!!2!!0 : []
endgame :: Board -> Result -> IO ()
endgame board result = do
displayBoard board
if result `elem` [XWin, OWin]
then
let player = if result == XWin then PX else PO
in do
putStrLn ("The game is over, and " ++ show player ++ " wins!")
putStrLn ((if player == PX then show PO else show PX) ++ " is a loser lol")
else do
putStrLn "The game is a tie"
putStrLn "You are both losers! Ugh!"
putStrLn "Want to play again? (y/n)"
again <- getLine
if again `elem` ["y", "Y", "yes", "Yes", "YES"]
then gameSelect
else do
putStrLn "Goodbye"
<小时/>
编辑:特别感谢@Chi 和@Caridorc,我做了以下更改。进一步的建议也将被考虑和更新
import Data.List
import Data.Char
import Data.Maybe
import Control.Monad
data Square = A | B | C | D | E | F | G | H | I | X | O deriving (Read, Eq, Ord)
instance Show Square where
show A = "a"
show B = "b"
show C = "c"
show D = "d"
show E = "e"
show F = "f"
show G = "g"
show H = "h"
show I = "i"
show X = "X"
show O = "O"
type Row = [Square]
type Board = [Row]
data Player = PX | PO deriving (Read, Eq)
instance Show Player where
show PX = "Player X"
show PO = "Player O"
data Result = XWin | Tie | OWin deriving (Read, Show, Eq, Ord)
main :: IO ()
main = do
putStrLn "Let's play some tic tac toe!!!"
putStrLn "Yeeeaaaaaahh!!!"
gameSelect
gameSelect :: IO ()
gameSelect = do
putStrLn "Who gonna play, one playa or two??? (Enter 1 or 2)"
gameMode <- getLine
case gameMode of
"1" -> onePlayerMode
"2" -> twoPlayerMode
_ -> gameSelect
where onePlayerMode = do
putStrLn "One playa"
putStrLn "Cool! Get ready to play...AGAINST MY INVINCIBLE TIC TAC TOE AI!!!!! HAHAHAHA!!!"
gameLoop 1 emptyBoard PX
twoPlayerMode = do
putStrLn "Two players"
gameLoop 2 emptyBoard PX
emptyBoard = [[A,B,C],[D,E,F],[G,H,I]]
displayBoard :: Board -> IO ()
displayBoard board = do
mapM_ print board
otherPlayer :: Player -> Player
otherPlayer PX = PO
otherPlayer PO = PX
gameLoop :: Int -> Board -> Player -> IO ()
gameLoop noOfPlayers board player = do
case detectWin board of
Just res -> endgame board res
Nothing -> case noOfPlayers of
1 -> case player of
PX -> enterMove 1 board player
PO -> enterBestMove board PO
2 -> enterMove 2 board player
enterMove :: Int -> Board -> Player -> IO ()
enterMove noOfPlayers board player = do
displayBoard board
case noOfPlayers of
1 -> do putStrLn ("Make your move. (A-I)")
2 -> do putStrLn (show player ++ ", it's your turn. (A-I)")
move <- getLine
print move
if not $ move `elem` ["a","b","c","d","e","f","g","h","i"] then do
putStrLn $ move ++ " is not a move, doofus"
gameLoop noOfPlayers board player
else if (read (map toUpper move) :: Square) `elem` (concat board) then do
gameLoop noOfPlayers (newBoard (read (map toUpper move) :: Square) player board) (otherPlayer player)
else do
putStrLn "That square is already occupied"
gameLoop noOfPlayers board player
enterBestMove :: Board -> Player -> IO ()
enterBestMove board player = gameLoop 1 (newBoard bestmove player board) PX
where bestmove = fst $ findBestMove PO board
findBestMove :: Player -> Board -> (Square, Result) -- minimax algorithm
findBestMove player board
| player == PO = findMax results
| player == PX = findMin results
where findMin = foldl1 (\ acc x -> if snd x < snd acc then x else acc)
findMax = foldl1 (\ acc x -> if snd x > snd acc then x else acc)
results = [ (sq, getResult b) | (sq, b) <- boards player board ]
getResult b = case detectWin b of
Nothing -> snd (findBestMove (otherPlayer player) b)
Just x -> x
boards :: Player -> Board -> [(Square, Board)]
boards player board = [(sq, newBoard sq player board) | sq <- concat board, sq /= X, sq /=O]
newBoard :: Square -> Player -> Board -> Board
newBoard move player board = [ [if sq == move then mark else sq | sq <- row] | row <- board]
where mark = if player == PX then X else O
detectWin :: Board -> (Maybe Result)
detectWin board
| [X,X,X] `elem` (triplets board) = Just XWin
| [O,O,O] `elem` (triplets board) = Just OWin
| [X,X,X,X,X,O,O,O,O] == (sort $ concat board) = Just Tie
| otherwise = Nothing
triplets :: Board -> [[Square]]
triplets board = board ++ transpose board ++ [diagonal1] ++ [diagonal2]
where
flat = concat board
diagonal1 = [flat !! 0, flat !! 4, flat !! 8]
diagonal2 = [flat !! 2, flat !! 4, flat !! 6]
endgame :: Board -> Result -> IO ()
endgame board result = do
displayBoard board
putStrLn $ endGameMessage result
putStrLn "Want to play again? (y/n)"
again <- getLine
if again `elem` ["y", "Y", "yes", "Yes", "YES"]
then gameSelect
else do
putStrLn "Goodbye"
endGameMessage :: Result -> String
endGameMessage result
| result `elem` [XWin, OWin] = winnerNotice ++ loserNotice
| otherwise = "The game is a tie\n" ++ "You are both losers! Ugh!"
where
winner = case result of
XWin -> PX
OWin -> PO
winnerNotice = "The game is over, and " ++ show winner ++ " wins!\n"
loserNotice = (show $ otherPlayer winner) ++ " is a loser lol"
最佳答案
代码风格通常是个人喜好的问题,在 Haskell 中可以说比其他具有“标准”风格指南的语言更重要。尽管如此,这里还是有一些随机的建议。
<小时/>不要过度缩进case
:只需使用另一行
case gameMode of "1" -> onePlayerMode
"2" -> twoPlayerMode
gameMode -> gameSelect
对比
case gameMode of
"1" -> onePlayerMode
"2" -> twoPlayerMode
gameMode -> gameSelect
甚至
case gameMode of
"1" -> onePlayerMode
"2" -> twoPlayerMode
_ -> gameSelect
<小时/>
case
通常优先于 if .. == Constructor
:
if player == PX
then enterMove 1 board player
else enterBestMove board PO
对比
case player of
PX -> enterMove 1 board player
PY -> enterBestMove board PO
<小时/>
我强烈建议不要使用像 fromJust
这样的部分函数,因为如果您忘记事先检查 Nothing
,它们可能会导致您的程序崩溃。存在更安全的替代方案,它们永远不会导致此类崩溃——减轻程序员的负担。
if detectWin b == Nothing
then snd (findBestMove (if player == PX then PO else PX) b)
else fromJust $ detectWin b
对比
case detectWin b of
Nothing -> snd $ findBestMove (if player == PX then PO else PX) b
Just x -> x
或
fromMaybe (snd $ findBestMove (if player == PX then PO else PX) b)
$ detectWin b
<小时/>
尝试分解常用函数。例如
nextPlayer PX = PO
nextPlayer PO = PX
可以替代使用
if player == PX then PO else PX
<小时/>
当只有一条语句时,不需要 do
:
if noOfPlayers == 1
then do putStrLn ("Make your move. (A-I)") -- no need for parentheses here
else do putStrLn (show player ++ ", it's your turn. (A-I)")
<小时/>
既然您在标题中提到了 where
,那么我要声明的是,总的来说,我对 where
的感受很复杂。我知道我经常倾向于避免 where
而支持 let
,但这种感觉并不与许多其他 Haskeller 一样,所以要小心一点。
就我个人而言,我倾向于将 where
的使用限制为单行:
foo = f x y
where x = ...
y = ...
特别是在可能跨越多行的do
block 中,我更喜欢let
s:
foo = do
line
line using x -- what is x ??!?
line
...
line
where x = ... -- ah, here it is
对比
foo = do
line
let x = ...
line using x
line
...
line
但是,请随意采用您认为更具可读性的样式。
<小时/>另外,不要忘记添加一些评论,正如@mawalker 指出的那样。有些定义是显而易见的,不需要任何解释。其他人可以从几行解释目的中受益。
关于haskell - Where 子句的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34663638/
我试图从一些 sql 查询中获得一些额外的性能,这些查询在一个字段上有一个 where 子句,它是一个非唯一的非聚集索引,它也是表 A 中的一个外键。该外键是主键在表 B 上,是聚集索引。 我想知道的
当包含在 FOR 中时,应该如何编写此 WMIC 命令脚本中的命令? wmic service where (name="themes" and state="running") get 下面的代码不
请帮我理解如何订购 对over子句的影响。我已经阅读了 msdn 和一本书,但仍然误解了。 假设我们有这样的查询: SELECT Count(OrderID) over(Partition By Ye
参见如下SQL语句: SELECT datediff("d", MAX(invoice.date), Now) As Date_Diff , MAX(invoice.date) AS ma
不知何故,对我来说构建这样的查询有点困难:给我所有链接名称不为空的导航条目 $query = $this->db->get_where('navigation',array('linkname'!==
我一直在寻找这个,但没有发现任何特别的东西。 是否可以有一个像 ALL IN 一样的 SQL 查询?为了更好地解释,这是一个表结构。 Orders table OrderItem table (hav
SELECT DISTINCT Campaign_id FROM Impressions WHERE Date BETWEEN '2015-03-01' AND '2015-03-31' ; 上述查询
我尝试在 MyBatis 中遵循 if 子句并得到以下异常请帮助我确定这里的问题.. public class Student{ private Integer studId; private Str
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
我尝试在 MyBatis 中遵循 if 子句并得到以下异常请帮助我确定这里的问题.. public class Student{ private Integer studId; private Str
是否可以用 where in 子句做这样的事情,我需要使用 where in 查询以下数据。 select * FROM instructor AS i INNER JOIN teaches AS t
嗨,我怎样才能让这个查询工作。我想要一个关于 where 子句的条件,如果 @BACHNUMB = '',那么 WHERE 是 (h.sopnumbe = @SOPNUMBE) 否则 WHERE 是
我在 MVC3 项目中工作。我浏览了一段时间并尝试了几个示例,但无法正常工作。 我需要从 OrderForm 表中获取记录列表,其 DeptID 在我已经获得的另一个列表中。 我知道我需要使用 Con
select * from staff LEFT JOIN servicereservation on servicereservation.snic = staff.snic where servi
我正在尝试使用 MySQL 创建带有“WITH”子句的 View WITH authorRating(aname, rating) AS SELECT aname, AVG(quantity)
我正在尝试使用 MySQL 创建触发器,但遇到错误。限制是:用户不得对他或她同时销售的商品出价。 Create Trigger before_insert_bid Before Insert on B
我正在尝试在 PostgreSql 的 WHERE IN 子句中使用 split_part,如下所示。这里 Objcode 是 small int 类型,objection 可能像 1374,824,
这可能很简单,只是我太厚了 - 我试图阻止保留的元素在记录中被拾取,但只有当库存大于 0 时,我不知道该怎么做除非 "....WHERE blah blah AND (reserved = 0 OR
我总结了两个表中两列的行,即如下所示: SUM( tableA.age ) + sum( tableB.age) as 'Total Ages' 但在某些情况下,A表的结果为空,而B表的结果则不是。在
我写了一个查询,从出生日期字段开始计算出一个人的年龄,然后使用 AS age 创建一个年龄字段。 我的问题是,是否可以再次匹配那个年龄字段? 像这样, SELECT `candidates`.`can
我是一名优秀的程序员,十分优秀!