简体   繁体   English

在 Haskell 中对字符串列表中的字符串进行编号

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

So I have to number each string in list of strings所以我必须给字符串列表中的每个字符串编号

Like this:像这样:

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

I tried this:我试过这个:

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

but of course it didn't work但当然没有用

In Haskell variables are immutable , so you can not change the value of a variable like in an imperative language like Python.在 Haskell 中变量是不可变的,所以你不能像 Python 这样的命令式语言那样改变变量的值。

You can for example use zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] to zip the list of strings together with a list of Int s:例如,您可以使用zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]将字符串列表与Int列表一起压缩:

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

Here f thus takes an Int and a String and produces a string " i : s " with i the string representation of the number, and s the string.这里f因此接受一个Int和一个String并产生一个字符串" i : s "其中i是数字的字符串表示, s是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM