How do I create a function with conditionals in it?

resolvent's picture

Simplest example I can think of.
I want to define f(x) to be the absolute value function
(yes, of course, without using the built-in Maple absolute value
function)

f:=x->x;

is great for defining a function. I've used that many times to
define n-vector-valued functions of m variables.
But how do I do

f:=x->x if x>0
f:=x->-x if x<0

I already tried putting f(x) INSIDE a conditional, namely

if(x>0) then f:=x->x
else f:=x=>-x;
end if:

but Maple doesn't remember my definition for f.
f(9); f(-4):
returns
f(9); f(-4);

Thanks.

two ways for your function

Here are two possibilities:

f:=proc(x)
if x>0 then x else -x;
fi;
end proc;

or

f:=x->piecewise(x>0,x,-x);

resolvent's picture

Procedures

Thanks, Alex Smith!
But, the output of your code seems to be just the code itself.
However, thank you for introducing me to a new set of commands
Procedures. I will have many questions very soon about that.

gkokovidis's picture

procedures

You can suppress the output from being echoed back to the screen by replacing the ending semicolon ( ; ) after the word "proc" by a colon ( : ). The procedure would look like this:

>f:=proc(x)
if x>0 then x else -x;
fi;
end proc:

You would call it just like before. Take a look at the help pages and you can also do a Google search for "Maple procedures".

Regards,
Georgios Kokovidis
Dräger Medical

Doug Meade's picture

unevaluated procedures

I'll guess that the real question is that you don't like Maple's response when you give f a non-numeric argument:

f := proc(x)
  if x>0 then x else -x fi;
end proc:
f(-3);
                                      3
f(x);
Error, (in f) cannot determine if this expression is true or false: 0 < x

The problem here is that Maple can decide if x>0 only when x is numeric.

In this type of situation you need to check if the argument is numeric before entering the body of the procedure. And, if you want, you can have Maple generate appropriate output. Here's one way to do this for your example:

f := proc(x)
  if x::numeric then
    if x>0 then x else -x end if;
  else
    nprintf("|%a|",x)
  fi;
end proc:
f(x);
                                     |x|
f(-3);
                                      3
f(2.44);
                                    2.44

Hoping this has been helpful,

Doug

---------------------------------------------------------------------
Douglas B. Meade
Math, USC, Columbia, SC 29208  E-mail: mailto:meade@math.sc.edu       
Phone:  (803) 777-6183         URL:    http://www.math.sc.edu/~meade/

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
}