Haskell打印带有某些格式的列表

Haskell打印带有某些格式的列表,haskell,Haskell,几天前刚开始学习Haskell,我遇到了一些问题。第一期涉及打印数字列表。所需的行为如下所示: 输入:[1,2,3,4,5,6] 产出:1 2 3 | 4 5 6 所以这是一个简单的概念,我只需要输出一个列表中的元素,在每三个数字之间插入|符号,但我无法用我的一生来理解它。似乎我尝试过的大部分内容都涉及字符串,即使我能够将列表设置为字符串,例如[1,2,3,…],我尝试过的所有方法都会在各自的行上打印数字,这不是我所需要的 任何帮助都将不胜感激 你可以这样做 threes [] = "" thr

几天前刚开始学习Haskell,我遇到了一些问题。第一期涉及打印数字列表。所需的行为如下所示:

输入:[1,2,3,4,5,6]

产出:1 2 3 | 4 5 6

所以这是一个简单的概念,我只需要输出一个列表中的元素,在每三个数字之间插入|符号,但我无法用我的一生来理解它。似乎我尝试过的大部分内容都涉及字符串,即使我能够将列表设置为字符串,例如[1,2,3,…],我尝试过的所有方法都会在各自的行上打印数字,这不是我所需要的

任何帮助都将不胜感激

你可以这样做

threes [] = ""
threes xs = let (front,rest) = splitAt 3 xs in
   unwords (map show front) ++ 
      if null rest then "" else " | " ++ threes rest
给予

*Main> threes [1..10]
"1 2 3 | 4 5 6 | 7 8 9 | 10"
我使用的功能:

splitAt :: Int -> [a] -> ([a], [a])
  -- splitAt 2 "Hello Mum" = ("He","llo Mum")

unwords :: [String] -> String
  -- unwords ["Hello","there","everyone"]
  --        = "Hello there everyone"

null :: [a] -> Bool
null [] = True
null _ = False
这里有一条路

import Data.List (cycle)

format :: Show a => [a] -> String
format = concat . zipWith (++) ("" : cycle [" ", " ", " | "]) . map show
这确实有一个缺点,即三人一组的分组是硬编码的,但推广起来并不太困难。

使用最近添加到Haskell平台的软件包:

> import Data.List         -- for intercalate
> import Data.List.Split   -- for chunksOf
> intercalate " | " . map unwords . chunksOf 3 $ map show [1..7]
"1 2 3 | 4 5 6 | 7"

相关文档:,。

第一部分最简单,您需要将数字转换为字符串

是这样的。然后我们需要将任何列表拆分为三个更一般的n个元素的块。splitAt将列表拆分为所需元素数的前面部分(如果列表足够长)和剩余部分。在余数不是空的情况下,对余数迭代该过程将得到所需的结果

chunk :: Int -> [a] -> [[a]]
chunk _ [] = []
chunk n xs = ys : chunk n zs
  where
    (ys, zs) = splitAt n xs
这是一个循环模式,所以有一个组合符,我们也可以写

import Data.List (unfoldr)

chunk :: Int -> [a] -> [[a]]
chunk n = unfoldr split
  where
    split [] = Nothing
    split xs = Just $ splitAt n xs
所以我们可以继续我们的模式

然后我们需要在所有块之间插入一个|,这是通过插入Data.List来完成的,最后,用空格连接所有字符串,这就是unwords所做的,所以


哇!谢谢,正是我所需要的。我找不到模块数据。List.Split'`。
import Data.List (unfoldr)

chunk :: Int -> [a] -> [[a]]
chunk n = unfoldr split
  where
    split [] = Nothing
    split xs = Just $ splitAt n xs
format :: (Num a, Show a) => [a] -> String
format xs = result
  where
    strings = map show xs
    chunks = chunk 3 strings
format :: (Num a, Show a) => [a] -> String
format xs = result
  where
    strings = map show xs
    chunks = chunk 3 strings
    result = unwords $ intercalate "|" chunks
format = unwords . intercalate "|" . chunk 3 . map show