Haskell打印输出二维数组
我试图在《生活游戏》中打印出我的2d阵列,但我不太确定如何继续。所以我需要一些关于printArray函数的帮助,我不太确定如何继续。她的密码如下,一切正常。。除了用正确的方式打印出来Haskell打印输出二维数组,haskell,multidimensional-array,Haskell,Multidimensional Array,我试图在《生活游戏》中打印出我的2d阵列,但我不太确定如何继续。所以我需要一些关于printArray函数的帮助,我不太确定如何继续。她的密码如下,一切正常。。除了用正确的方式打印出来 module GameOfLife where import Data.List import System.IO import Text.Show import Data.Array import System.Random width :: Int width = 5 height :: Int heig
module GameOfLife where
import Data.List
import System.IO
import Text.Show
import Data.Array
import System.Random
width :: Int
width = 5
height :: Int
height = 5
data State = Alive | Dead deriving (Eq, Show)
type Pos = (Int,Int)
type Board = Array Pos State
startBoard :: Pos -> Board
startBoard (width,height) =
let bounds = ((0,0),(width - 1,height - 1))
in array bounds $ zip (range bounds) (repeat Dead)
set :: Board -> [(Pos,State)] -> Board
set = (//)
get :: Board -> [Pos] -> [State]
get board pos = map (board!) pos
neighbours :: Board -> Pos -> [Pos]
neighbours board c@(x,y) =
filter (/= c) $ filter (inRange (bounds board)) [(x',y') | x' <- [x -
1..x + 1], y' <- [y - 1..y + 1]]
nextGen :: Board -> Board
nextGen board =(irrelevant code for the question..)
printArray :: Board -> String
printArray arr =
unlines [unwords [show (arr ! (x, y)) | x <- [1..5]] | y <- [1..5]]
我比较喜欢的输出:
1 2 3 4 5
1 . . . . .
2 n n n . .
3 n X n . .
4 n n n . .
5 . . . . .
为了开始回答您的问题,我建议将问题分成几部分:
一次解决一个问题。如果有用的话,与其考虑“打印”,不如构建一个
字符串对象。一旦你有了一个字符串
,打印就非常简单了。请将你的代码减少到最少,以说明你的问题。例如,nextGen
函数似乎与您的问题无关。您可以创建硬编码的板
进行打印。此外,显示您实际获得的输出,并解释它与您想要的不同之处。有关改进问题以吸引您想要的答案的更多提示,请参阅,我认为我的下一步与se如何工作相关。但是现在我已经修正了我的输出建议。你的问题是关于打印的。唯一重要的数据是打印功能的输入。这些数据从何而来无关紧要。数据的格式非常重要。您需要弄清楚如何将输入数据的格式转换为您希望输出的格式。作为程序员,将问题分解为小部分是一项极其重要的技能。这意味着您需要专注于对当前问题非常重要的细节,而忽略其他一切。您也可以从另一个角度来思考:编译printary
需要什么代码?扔掉任何不是绝对必要的东西。首先,我将尝试这种方法,谢谢。我会回到你身边!
1 2 3 4 5
1 . . . . .
2 n n n . .
3 n X n . .
4 n n n . .
5 . . . . .