标准ML:使用foldr从int列表中创建字符串

问题描述

我正在尝试在Standard ML中创建一个函数,以从int列表[1,2,3,4]中创建一个字符串,使其看起来像"1,4"

我设法创建的函数可以通过迭代并转换为字符串并添加“,”来完成这项工作。但是由于我在每次迭代后都将逗号都收起来,所以逗号也将最终出现在字符串的末尾。

这是我的功能:

fun list_string lst =
    (foldr (fn (x,y) => x ^ "," ^ y ) "" (List.map (fn x => Int.toString(x)) lst));

您会看到一个问题,当它到达末尾时,它仍然会打印逗号。 有没有办法我可以用文件夹将功能添加到零件中,以便它可以检查最后一个元素?

解决方法

仅当您不在列表的第一项时,才可以添加逗号。可以通过将y与空字符串进行比较来简单地进行检查:

fun list_string lst = (List.foldr (fn (x,y) => if y = "" then x else x ^ "," ^ y)
                  "" (List.map (fn x => Int.toString(x)) lst));

print(list_string([1,2,3]));

您也可以通过模式匹配来做到这一点,而无需先将int列表映射到字符串列表。因此,您只遍历列表一次。我认为这也更具可读性:

fun list_string lst = List.foldr (
      fn (x,"") => (Int.toString x)
      |  (x,y)  => (Int.toString x) ^ "," ^ y) "" lst;
print(list_string([1,3]));
,

您可以通过折叠来实现:

fun commaSep [] = ""
  | commaSep (n0::ns) =
      foldl (fn (n,s) => s ^ "," ^ Int.toString n) 
            (Int.toString n0)
            ns

或者您可以使用concatmapintersperse

fun intersperse x [] = []
  | intersperse x [y] = [y]
  | intersperse x (y::zs) = y :: x :: intersperse x zs

val commaSep = String.concat
             o intersperse ","
             o List.map Int.toString

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...