簡體   English   中英

Haskell:從列表中一一打印 Int

[英]Haskell: Print Int from list one by one

關於我想在 Haskell 中做的事情,我有一個簡短的問題。 我的主要目標是制作一個從 1 到特定值 y 的整數列表。 像 [1..y] 一樣,打印這個列表,每個數字之間有空格

假設我有 [1..8]

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

_1_2_3_4_5_6_7_8

我玩過一些不同的東西,但沒有任何運氣

這基本上是我到目前為止所得到的

printLst :: [Int] -> String
printLst (x:xs) = " " ++ putStr (show x) >> printLst xs

我一直在搜索 web 以找到任何解決方案,但我沒有找到任何可以幫助我做到這一點的東西。

非常感謝幫助

首先,定義一個 function 將Int轉換為String ,然后在結果前面加上一個空格。

\x -> ' ' : show x

現在 map 在您的列表中:

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

現在我們只需要將所有字符串連接成一個:

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

這可以使用concatMap function 來簡化:

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

其中 forms 是Monad實例列表的基礎:

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

或者更簡單地說,使用 function 組合

> [1..8] >>= (' ' :) . show
" 1 2 3 4 5 6 7 8"

一旦你有了最終的字符串,現在你可以擔心打印它了。

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

好吧,首先,您在這里混淆了事物:

putStr :: String -> IO ()

而且您正在返回一個String ,因此無需使用它。 此外,您沒有[]和 singleton 列表的模式,您可以添加它們以獲得更好的 output ,如下所示:

printLst :: [Int] -> String
printLst [] = ""
printLst [x] = (show x)
printLst (x:xs) = (show x) ++ " " ++ printLst xs

如果要使用IO () function,在主function中使用:

main = do
  putStrLn (printLst [1..8])

這是一個列表處理問題。 對於空列表,我們可以返回空字符串,對於非空列表,我們可以先產生一個空格,然后show該項目,然后在該列表的 rest 上遞歸,如:

prefixSpace :: Show a => [a] -> String
prefixSpace [] = ""
prefixSpace (x:xs) = ' ' : show x ++ prefixSpace xs

或作為“折疊”模式:

prefixSpace :: Show a => [a] -> String
prefixSpace = foldr (\x -> ((' ' : show x) ++)) ""

不會打印字符串。 為此,您需要putStrLn:: String -> IO () ,但正如簽名所示,如果您putStrLn some_string ,您將使用IO ()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM