You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell列表元素编号实现问题:禁用递归仅用高阶函数

实现Haskell的numberLines函数(高阶函数版)

完整代码

numberLines :: [String] -> [String]
numberLines = map (\(n, s) -> show n ++ ": " ++ s) . zip [1..]

解决你的两个问题:

  • 实现计数器:用zip把输入列表和无限整数序列[1..]配对。zip会自动按输入列表的长度截断,每个元素都会带上从1开始的序号,完全不用手动维护计数器。
  • Int转字符串拼接:Haskell里++只能拼接同类型的字符串,所以先用show把Int转成String(比如show 3得到"3"),之后就能和: 以及原字符串正常拼接了。

验证示例

输入:["asd qwe", "-- Foo", "", "\thello world "]
经过zip [1..]得到配对列表:[(1,"asd qwe"),(2,"-- Foo"),(3,""),(4,"\thello world ")]
再经过map处理后,输出就是你要的:["1: asd qwe", "2: -- Foo", "3: ", "4: \thello world "]

内容的提问来源于stack exchange,提问作者Tamás Veszelyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:25:19