【问题标题】:How to work with labels in mozart oz to get the elements from pair/tuple?如何使用 mozart oz 中的标签从对/元组中获取元素?
【发布时间】:2019-11-23 10:55:20
【问题描述】:

我是 mozart oz 的新手,我有这个问题要解决:

  a) Implement a function Zip that takes a pair Xs#Ys of two lists Xs and Ys (of the
 same length) and returns a pairlist, where the first field of each pair is taken
 from Xs and the second from Ys. For example, {Zip [a b c]#[1 2 3]} returns the
 pairlist [a#1 b#2 c#3].

  b) The function UnZip does the inverse, for example {UnZip [a#1 b#2 c#3]}
 returns [a b c]#[1 2 3]. Give a specification and implementation of UnZip.

我所知道的是# 是某种标签,它构成一对/元组,取自文档,但我找不到说明如何使用它的示例。

我的问题是如何拆分它以获取项目或如何使用该标签(或任何可能有如何使用它的示例的来源)。

我做了一些搜索,我得到了这段代码(我不知道它在语法上是否正确):


    declare
    fun {Zip L}
       case L of nil then nil
       [] L1#L2 then .... % Here i'm stuck or i don't know how to proceed
       end
    end

    {Browse {Zip ['a' 'b' 'c']#[1 2 3]}}

任何帮助将不胜感激。

感谢您的宝贵时间。

【问题讨论】:

    标签: paradigms oz mozart


    【解决方案1】:

    基本上,Oz 中的模式匹配是最强大的工具之一。我们不能使用 for 循环,因为变量是不可变的,所以我们使用递归。

    functor
    import
        System
        Application
    define
        fun {Zip L}
          case L of L1#L2 then
            case L1 of H1|R1 then
              case L2 of H2|R2 then
                H1#H2|{Zip R1#R2}
              else nil end
            else nil end
          else nil end
        end
        {System.show {Zip ['a' 'b' 'c']#[1 2 3]}} 
    
        % Shows [a#1 b#2 c#3]
    
        {Application.exit 0}
    end
    

    【讨论】:

    • 这段代码如何解决所描述的问题?请详细说明
    • 谢谢,第一个要求已经解决了,但现在我卡在 UnZip 功能上。你能提供一个如何解决它的提示吗?谢谢 :)
    • 我设法做到了这一点declare fun {UnZip L S F} case L of nil then S#F [] H|T then case H of H1#H2 then {UnZip T H1|S H2|F} else nil end end end {Browse {UnZip [a#1 b#2 c#3] nil nil}} % Shows [c b a]#[3 2 1] % Should show [a b c]#[1 2 3] 但它以相反的顺序返回列表,有什么建议让它正确显示吗?
    【解决方案2】:

    您只需要一个反转列表的函数:

        declare
        fun {ReverseAux L1 L2}
           case L1
           of nil then L2
           [] H|T then {ReverseAux T H|L2}
           end
        end
        
        
        % wrapper for reverse
        
        declare
        fun {Reverse L}
           {ReverseAux L nil}
        end
        
        
    

    那么,你的 UnZip 函数可以这样写:

        declare
        fun {UnZipAux L S D}
           case L
           of nil then {Reverse S}#{Reverse D}
           [] X#Y|T then {UnZipAux T X|S Y|D}
           end
        end
    
        
        % wrapper for UnZip
    
        declare
        fun {UnZip L}
           {UnZipAux L nil nil}
        end
    

    希望你做得好兄弟,这也是我目前的作业:))

    【讨论】:

      猜你喜欢
      • 2012-02-06
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      相关资源
      最近更新 更多