[英]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.