Search code examples
ozmozart

Duplicate the elements of a list OZ


Write a function that duplicates every element in a list. For instance: {Duplicate [1 2 3]} returns the list [1 1 2 2 3 3].

How can I make it in OZ mozart? I don't know the sintaxis of oz, in prolog would be something like:

even(N) :- 
    N mod 2 =:= 0.    

doubleeven([],[]).

doubleeven([H|T], [H,H|Z]) :-
    even(H),
    !,
    doubleeven(T,Z).

doubleeven([H|T], [H|Z]) :-
    doubleeven(T,Z).

Solution

  • This is a solution based on pattern recognition. You check if the incoming data is a list (i.e., it has a Head and a Tail (H|T)), and then the first element is bound to the variable identifier H. That way you can just do the repeat by adding two H's before you go on to do the same thing with the rest of the list. Remember to return nil if L is nil -- the empty list, so that your final answer is a list as well.

    declare
    fun {Duplicate L}
       case L of H|T then
          H|H|{Duplicate T}
       else
          nil
       end
    end
    
    {Browse {Duplicate [1 2 3]}}