gpt4 book ai didi

Haskell : How do I compose a recursive function that takes an element and gives gives back its list, 但有不同的数据类型?

转载 作者:行者123 更新时间:2023-12-01 09:35:21 27 4
gpt4 key购买 nike

假设我有如下数据类型:

 data Cell = Cell (Maybe Player)
data Board = Board [[Cell]]

现在我想生成一个这样的递归函数:

 genBoard :: [Cell] -> Board
genBoard [] = []
genBoard c = (take 3 c) : (genBoard $ drop 3 c) -- takes list of 9 Cells and gives 3x3 list of cells

显然,上述代码失败了,因为 (:) 不能将 [Cell] 添加到 Board,尽管从技术上讲,Board 只不过是 [[Cell]]。我需要将 Board 作为单独的数据类型来为其提供我自己的显示功能。

到目前为止,我想出的最好的是:

genBoardList :: [Cell] -> [[Cell]]
genBoardList [] = []
genBoardList c = (take 3 c) : (genBoardList $ drop 3 c)

boardListToBoard :: [[Cell]] -> Board
boardListToBoard [] = Board []
boardListToBoard s = Board s

genBoard :: [Cell] -> Board
genBoard = boardListToBoard . genBoardList

但这似乎有点太长了,而且很难完成一件看似简单的事情。有什么想法可以改进我的代码吗?

最佳答案

您只需使用模式匹配从 Board 构造函数中解开列表,然后在每个步骤中将其重新包装;例如,使用 let...in:

genBoard :: [Cell] -> Board
genBoard [] = []
genBoard cs =
let Board css = genBoard (drop 3 cs)
in Board (take 3 cs : css)

或者,更惯用的,where 子句:

genBoard :: [Cell] -> Board
genBoard [] = []
genBoard cs = Board (take 3 cs : css)
where
Board css = genBoard (drop 3 cs)

另一个改进是使用模式匹配代替 takedrop:

genBoard :: [Cell] -> Board
genBoard [] = []
genBoard (c0:c1:c2:cs) = Board $ [c0, c1, c2] : css
where
Board css = genBoard cs

您还可以使用 split 使其更简单包装:

genBoard :: [Cell] -> Board
genBoard = Board . splitEvery 3

关于Haskell : How do I compose a recursive function that takes an element and gives gives back its list, 但有不同的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9152396/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com