我将如何遍历SMLNJ中的列表。我已经在这里待了三个小时了,我一生都无法解决。
因此,仅遍历并打印列表即可。用最简单的方法[5,2,3]可以打印出5 2 3或此列表的变体。
答案 0 :(得分:2)
我将如何遍历SMLNJ中的列表
这取决于您要执行的遍历类型:映射,折叠,迭代。
使用递归:
(* mapping: *)
fun incr_each_by_1 [] = []
| incr_each_by_1 (x::xs) = x + 1 :: incr_each_by_1 xs
val demo_1 = incr_each_by_1 [5,2,3] (* [6,3,4] *)
(* folding: *)
fun sum_all_together [] = 0
| sum_all_together (x::xs) = x + sum_all_together xs
val demo_2 = sum [5,2,3] (* 10 *)
(* iteration: *)
fun print_each [] = ()
| print_each (x::xs) = ( print (Int.toString x ^ "\n") ; print_each xs )
val demo_3 = print_each [5,2,3] (* no result, but side-effect *)
使用高阶函数:
val demo_1 = List.map (fn x => x + 1) [5,2,3]
val demo_2 = List.foldl (fn (x, result) => x + result) 0 [5,2,3]
val demo_3 = List.app (fn x => Int.toString x ^ "\n") [5,2,3]