首页 > 解决方案 > 如何打印出二维数组haskell

问题描述

我想打印出二维数组,例如

data a = b [[a]]  
instances Show a where  
show (b array) = "Array:\n" ++ show array   
array = [[(1, 2), (3, 4)],[(5, 6), (7, 8)]]

(我希望这个伪代码是可读的)

以这种方式:

[(1, 2), (3, 4)]\n
[(5, 6), (7, 8)]

我得到的唯一结果是:

[[(1, 2), (3, 4)], [(5, 6), (7, 8)]]

我需要使用实例显示。

标签: haskell2dinstancenested-listsshow

解决方案


我在 StackOverflow 上找到了一个关于list type 的重载显示函数的有趣链接。
代码:

{-# LANGUAGE FlexibleInstances #-}
module Main where
array = [[(1, 2), (3, 4)],[(5, 6), (7, 8)]]
main = putStrLn $ Main.show array

instance {-# OVERLAPPING #-} Show [[a]] where
show (a:x) = Prelude.show a ++ "\n" ++ Main.show x
show [] = ""

编译输出(不幸的是没有警告):

[1 of 1] Compiling Main             ( main.hs, main.o )

main.hs:6:30: warning: [-Wmissing-methods]
    * No explicit implementation for
        either `showsPrec' or `Prelude.show'
    * In the instance declaration for `Show [[a]]'
  |
6 | instance {-# OVERLAPPING #-} Show [[a]] where
  |                              ^^^^^^^^^^
Linking main ...

输出:

[(1,2),(3,4)]
[(5,6),(7,8)]

推荐阅读