首页 > 解决方案 > 在 Haskell 中对字符串列表中的字符串进行编号

问题描述

所以我必须对字符串列表中的每个字符串进行编号

像这样:

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

我试过这个:

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

但当然它没有用

标签: haskell

解决方案


在 Haskell 中,变量是不可变的,所以你不能像 Python 这样的命令式语言那样改变变量的值。

例如,您可以使用将字符串列表与szipWith :: (a -> b -> c) -> [a] -> [b] -> [c]列表一起压缩:Int

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

因此,此处f采用 aInt和 aString并生成一个字符串,其中包含数字的字符串表示形式和字符串。"i: s"is


推荐阅读