簡體   English   中英

在 Haskell 中對字符串列表中的字符串進行編號

[英]Numbering the strings in a list of strings in Haskell

所以我必須給字符串列表中的每個字符串編號

像這樣:

numberLines ["one", "two", "three"] 
   ==> ["1: one", "2: two", "3: three"]

我試過這個:

numberLines = map (\g -> (x + 1) : g) where
 x = 0

但當然沒有用

在 Haskell 中變量是不可變的,所以你不能像 Python 這樣的命令式語言那樣改變變量的值。

例如,您可以使用zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]將字符串列表與Int列表一起壓縮:

numberLines :: [String] -> [String]
numberLines = zipWith f [1 :: Int .. ]
    where f i s = show i ++ ' ' : ':' : s

: " with i the string representation of the number, and s the string.這里f因此接受一個Int和一個String並產生一個字符串" : "其中i是數字的字符串表示, s是字符串。

暫無
暫無

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

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