我目前正在用 SML 撰寫一個代碼,該代碼接收一個充滿數字和空格的字串串列。代碼必須將數字組合到空格,然后為下一組數字創建一個新的串列項,依此類推。
例如,串列["1", "", "2", "3", "", "4", "5", "6"]將回傳串列["1", "23", "456"]。
我當前的非錯誤嘗試包括以下代碼。
fun conc(L) =
case L of
[] => ""
| x::xs => x ^ conc(xs);
fun intParse(L as x::xs) =
let
val intStr = conc(L)
in
intStr :: intParse(xs)
end;
我想寫類似下面的代碼,但不能沒有錯誤。這不是確切的代碼,更像是我無法弄清楚的偽代碼。
fun strToInt(nil) = []
| strToInt(L) =
let
fun conc(y::ys) =
if hd(ys) <> "" then y ^ conc(ys)
else y ^ ""
in
conc(L) :: strToInt(xs)
end;
uj5u.com熱心網友回復:
當您在串列上遞回迭代時,您需要一個基本案例。你已經想通了。是[]。
您需要的另一件事是在迭代時可以傳遞的一個或多個累加器。這些累加器可以使用本地范圍的輔助函式“隱藏”,您可以向該函式提供處于初始狀態的累加器。
val lst = ["1", "", "2", "3", "", "4", "5", "6"];
fun lstTransform(lst) =
let
fun aux([], str, acc) =
if str = "" then List.rev(acc)
else List.rev(str :: acc)
| aux(x::xs, str, acc) =
if x = "" andalso str <> "" then
aux(xs, "", str :: acc)
else if x = "" then
aux(xs, "", acc)
else
aux(xs, str ^ x, acc)
in
aux(lst, "", [])
end;
當您遇到基本情況時,您想檢查您已構建的“當前”字串的累加器 ( str) 是否為空。如果它是空的,我們只回傳累加器。如果沒有,我們需要將該字串添加到累加器中。
在任何一種情況下,由于串列的構建方式,它們會倒退,所以我們反轉它們。
否則,您將評估串列中的第一個元素并根據該元素決定如何為下一次迭代更新您的狀態。
這種對串列的迭代和新值的累積正是List.foldl為此而設計的。這個函式讓我們擺脫了很多樣板。我們提供了一個作用于串列中每個元素和累加器的函式;以及累加器的初始狀態;以及要處理的串列。
let
val (str, acc) =
List.foldl
(fn (x, (str, acc)) =>
if x = "" andalso str <> "" then ("", str :: acc)
else if x = "" then ("", acc)
else (str ^ x, acc))
("", [])
lst
in
if str = "" then List.rev(acc)
else List.rev(str :: acc)
end;
uj5u.com熱心網友回復:
這是我的嘗試...
fun squoosh lst =
let
fun collect_and_accumulate acc collected =
fn [] => List.rev (if collected = "" then acc else collected :: acc)
| (""::ys) => collect_and_accumulate (if collected = "" then acc else collected :: acc) "" ys
| (x::ys) => collect_and_accumulate acc (collected ^ x) ys;
in
collect_and_accumulate [] "" lst
end;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/418419.html
標籤:
上一篇:使用遞回取陣列的平均值
