简体   繁体   English

在Haskell中输出列表列表?

[英]Outputting a list of lists in Haskell?

I am a complete beginner to Haskell but I'm being asked to create a sudoku solver. 我是Haskell的初学者,但我被要求创建一个数独求解器。 I've been making some steady progress with it but one of the things it is asking me to do is print a valid representation of a sudoku puzzle s. 我一直在用它做一些稳定的进步,但它要求我做的一件事就是打印一个有趣的数独谜题表示。 The Puzzle data type is defined as a list of lists, so [[Maybe Int]] and this is composed of Block values ( [Maybe Int] , representing a row). Puzzle数据类型被定义为列表列表,因此[[Maybe Int]]并且这由块值( [Maybe Int]表示一行)组成。

Function signature is this: 功能签名是这样的:

printPuzzle :: Puzzle -> IO ()

How do I output this? 我该如何输出? I know this may be a simple question and I'm missing the point but I'm still not at the stage where I've got my ahead around the syntax yet. 我知道这可能是一个简单的问题而且我错过了重点,但我还没有达到我在语法方面领先的阶段。 Any help would be much appreciated! 任何帮助将非常感激!

Simple pretty-printing of this can be done really succinctly with something like the following: 简单漂亮的打印可以通过以下方式非常简洁地完成:

import Data.Char (intToDigit)

showRow :: [Maybe Int] -> String
showRow = map (maybe ' ' intToDigit)

showPuzzle :: [[Maybe Int]] -> [String]
showPuzzle = map showRow

printPuzzle :: [[Maybe Int]] -> IO ()
printPuzzle = mapM_ putStrLn . showPuzzle
  • showRow takes a single row from your grid and prints it - using the maybe function from Data.Maybe , we can write this as a quick map from each Maybe Int value to either a default "blank space" value or the character representing the number (using intToDigit ). showRow从你的网格中获取一行并打印它 - 使用Data.Maybemaybe函数,我们可以将其作为从每个Maybe Int值的快速映射写入默认的“空格”值或表示数字的字符(使用intToDigit )。

  • showPuzzle simply maps showRow over the outer list. showPuzzle只是将showRow映射到外部列表。

  • printPuzzle just uses the previous pure definitions to give the impure action which prints a grid, by putStrLn 'ing the pretty-print of each row. printPuzzle只是使用以前的纯定义来给出打印网格的不纯动作,通过putStrLn每行的漂亮打印。


A quick demo: 快速演示:

> printPuzzle [[Just 1, Nothing, Just 3],
               [Nothing, Just 3, Just 6],
               [Just 2, Just 4, Just 5]]
1 3
 36
245

Though you can easily modify the above code to print something more explicit, like: 虽然您可以轻松修改上述代码以打印更明确的内容,例如:

1X3
X36
245

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM