How do you change an element in a list in Oz?

感情迁移 提交于 2019-12-13 07:30:49

问题


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 Swapso 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!