paradigmsozmozart

How to work with labels in mozart oz to get the elements from pair/tuple?


I'm new to mozart oz and I have this problems to solve:

  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.

All I know is that # is a label of some sort which composes a pair/tuple, taken from the docs, but I couldn't find an example that illustrates how to work with it.

My question is how to split it to get the items or how to work with that label (or any source that might have an example of how to work with it).

I've done a little bit of search and I arrived at this piece of code (I don't know if it's even correct syntactically):


    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]}}

Any help will be appreciated.

Thanks for your time.


Solution

  • Basically, pattern matching in Oz is one of the most powerful tools. We can't use for-loops, as varibles are unmutable, so we use recursion.

    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