Haskell:逐一打印列表中的Int

gol*_*iii 2 haskell list

关于我想在Haskell做的事情,我有一个简短的问题。我基本上要实现的目标是制作一个从1到特定值y的整数列表。像[1..y],并打印此列表,每个数字之间都有空格

假设我有[1..8]

我想要的输出是(“ _”代表空格):

_1_2_3_4_5_6_7_8
Run Code Online (Sandbox Code Playgroud)

我玩了一些不同的东西,但是没有运气

这基本上是我到目前为止所获得的

printLst :: [Int] -> String
printLst (x:xs) = " " ++ putStr (show x) >> printLst xs
Run Code Online (Sandbox Code Playgroud)

我一直在网上搜索以找到解决方案,但是没有找到任何可以帮助我完成此任务的方法。

非常感谢帮助

che*_*ner 6

首先,定义其转换的功能IntString,预先考虑然后对结果的空间。

\x -> ' ' : show x
Run Code Online (Sandbox Code Playgroud)

现在将此映射到您的列表中:

>  map (\x -> ' ' : show x) [1..8]
[" 1"," 2"," 3"," 4"," 5"," 6"," 7"," 8"]
Run Code Online (Sandbox Code Playgroud)

现在我们只需要将所有字符串连接成一个即可:

> concat (map (\x -> ' ' : show x) [1..8])
" 1 2 3 4 5 6 7 8"
Run Code Online (Sandbox Code Playgroud)

可以使用以下concatMap函数来简化:

> concatMap (\x -> ' ':show x) [1..8]
" 1 2 3 4 5 6 7 8"
Run Code Online (Sandbox Code Playgroud)

构成Monad列表实例的基础:

> [1..8] >>= (\x -> ' ' : show x)
" 1 2 3 4 5 6 7 8"
Run Code Online (Sandbox Code Playgroud)

甚至更简短地讲,使用函数组合

> [1..8] >>= (' ' :) . show
" 1 2 3 4 5 6 7 8"
Run Code Online (Sandbox Code Playgroud)

有了最终字符串后,现在您就可以担心要打印它了。

> putStrLn $ [1..8] >>= (' ' :) . show
 1 2 3 4 5 6 7 8
Run Code Online (Sandbox Code Playgroud)