SMLNJ 列表遍历
SMLNJ list traversion
我将如何遍历 SMLNJ 中的列表。我已经在这里待了 3 个小时了,我一辈子都弄不明白。
所以只是遍历并打印出一个列表。以最简单的方式 [5,2,3] 将打印出 5 2 3 或它的列表变体。
How would I go about traversing a list in 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]
我将如何遍历 SMLNJ 中的列表。我已经在这里待了 3 个小时了,我一辈子都弄不明白。
所以只是遍历并打印出一个列表。以最简单的方式 [5,2,3] 将打印出 5 2 3 或它的列表变体。
How would I go about traversing a list in 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]