我正在尝试将 Java 代码中的嵌套 for 循环转换为 SML。我将有一个格式列表 [[a, b, c], [d, e, f], [g, h, i]] 并且我希望这个函数给我一个表单列表 [ [a, d, g], [b, e, h], [c, f, i]]。每个列表的长度会有所不同,我需要避免使用任何可变数据类型。到目前为止我的代码是这样的——底部pointFromList
获取每个内部列表并将其放入我在其他地方定义的记录中。
我遇到的问题是下面的代码不会终止。查看调试输出,它在所有zipElement ([], xs::xss, accY, accX)
调用中都能正常工作,但在那之后它会在某个地方中断。我是 SML 的新手,我完全被难住了。
fun zipListToPoints (featuress : real list list) =
let
fun zipElement ([], [], accY, []) =
accY
| zipElement ([], [], accY, accX) =
zipElement(rev(accX), rev(accY), [], [])
| zipElement ([], xs::xss, accY, accX) =
zipElement([], xss, [hd(xs)]::accY, tl(xs)::accX)
| zipElement (ys::yss, xs::xss, accY, accX) =
zipElement (yss, xss, (hd(xs)::ys)::accY, tl(xs)::accX)
val numFeatures = length(hd(featuress))
val zippedList = zipElement([], featuress, [], [])
in
map pointFromList zippedList
end
end
更大的背景是我有一个point
带有标签的记录类型features : real list
。为了在对数据进行一些分析之前对其进行规范化,我需要features
对每个点的列表的第 i 个元素执行操作。原始 Java 如下所示:
for(i=0;i<Points.length(); i++){
oneFeature = new float[Points.getNumberOfFeatures()];
for(j=0; j<Points.getNumberOfFeatures(); j++){
oneFeature[j] = Points[j].getFeature(i);
}
normalizedData = new float[Points.getNumberOfFeatures()];
normalizedData = normalize(oneFeature);
for(k=0; k<Points.length(); k++){
Points[k].setFeatureList(normalizedData[k]);
}
}
我的 SML 最终应该看起来像:
fun normalizeData (points) =
let
fun extractFeature (index) =
map (fn features => sub(features, index)) #features(points)
val listOfFeatures =
map extractFeature list.Tabulate (length(points), fn x => x)
val normalizedFeatures =
map normalizeFeature listOfFeatures
in
map zipListToPoints normalizedFeatures
end
(所以有点弄乱了我的 SML 的缩进,对不起!)