问题
I want to swap an item in a list in oz.
So let's say I have L = [ 1 2 3], and I would like it to be L = [1 4 3].
How would one go about doing that? I see
{List.member X +Ys ?B}
And other various possible functions on https://mozart.github.io/mozart-v1/doc-1.4.0/base/list.html
But I don't really understand the syntax of these expressions. I am very new to Oz.
回答1:
If you want to swap a particular element numbered N, you can just iterate through the list until you find it, then replace it and keep the rest of the list in in place. This would be something like
declare
fun {Swap Xs N Y}
case Xs of nil then nil % There is no Nth element, the list doesn't change
[] X|Xr then
if N==1 then Y|Xr % Replace _ with Y and append the rest
else X|{Swap Xr N-1 Y} end % Continue to iterate through the list, but keep the previous elements of the list
end
end
You could also use an auxiliary function inside Swap
so you wouldn't have to pass Y around on every recursive call but I didn't want to bother you with the details since you're a beginner.
来源:https://stackoverflow.com/questions/26194783/how-do-you-change-an-element-in-a-list-in-oz