1

I need to do this two very similar exercises in Oz:

*. Write the function {Some L P} that takes a list L and a Boolean function P. It returns true if P returns true for at least one element of L and false otherwise.

*. Write the function {All L P} that returns true if and only if P is true for all the elements in L.

what I'm not sure is if I have a function like this, how can I make it return true or false:

    declare
fun{P X} //bolean function
   if X==2 then true
   else false
   end
end

fun{Some L P} //Some function
   case L
   of nil then nil
   [] X|Xr then
      if {P X} == true then X|{Some Xr P}
      else {Some Xr P}
      end
   end
end

{Browse {Some [1 2 3] P}} 

2 is true, so it has to return true

Zaz On Ira
  • 11
  • 2

2 Answers2

1

Some hints:

First, think about the desired result in case of an empty list. At the moment, you are returning nil. You probably should return false. Because in an empty list, there can not be any element which fulfills a predicate.

Then think about the case where you found one element for which P is true. I don't think you have to iterate through the rest of the list...

wmeyer
  • 3,426
  • 1
  • 18
  • 26
0

In function Some you are returning a nil value in case of an empty list, but you want a boolean value returned by the function, so it should be false as an empty list can not certainly fulfill the P function, whatever it is. Then, once you find an element that satisfy P, there's no need to check the rest of the list. You can use the Oz operator orelse, that works as the logic or operator but evaluate the second argument only if the first is false.

The function {All L P} will work in a similar way, now you can stop checking the list when you find an element that doesn't satisfy P, so you can use the Oz operator andthen. The only difference is that now you have to check when the list consist of one element (same issue when you evaluate the last one) because the function at the next step will evaluate a nil element returning false, making false all the function value in the andthen statement.

Last thing: line comments in Oz are in this form % My comments, not as you did with slashes.

Sorry for my long answer and for my english, the code should be:

declare
fun{P X}
   if X==2 then true
   else false
   end
end

fun{Some L P}
   case L
   of nil then false
   [] X|Xr then {P X} orelse {Some Xr P}
   end
end

fun{All L P}
   case L
   of nil then false
   [] [X] then {P X}
   [] X|Xr then {P X} andthen {All Xr P}
   end
end  

{Browse {Some [1 2 5] P}} 
{Browse {All [2 2 2 2] P}}
rok
  • 2,574
  • 3
  • 23
  • 44