|
![](/i/fill.gif) |
Wasn't it Jo Jaquinta who wrote:
>Hey Folks,
> I'm trying to create a sgn() function, like in BASIC. Where sgn(x) =
>-1 if x < 0, +1 if x > 0 and 0 if x = 0.
>
>First I tried with a function:
>
>#declare sgn = function(xx) { #if (xx<0) -1 #else #if (xx>0) 1 #else 0
>#end #end }
You can't use #if inside a function. You need to use "select".
This works:
#declare sgn=function(xx){select(xx,-1,0,1)}
>But this dies with a "expected 'numeric expression', undeclared
>identifier 'xx' found instead". I take this to mean you can't use a if
>inside a function.
>
>So I tried with a macro:
>
>#macro sgn(xx)
> #if (xx < 0)
> -1
> #else
> #if (xx > 0)
> 1
> #else
> 0
> #end
> #end
>#end
>
>But this gives me a Parse Error: Expected ')', # found instead on the
>"-1" line.
I don't know the details of why that doesn't work, but you can write it
quite neatly with the "?" operator.
This works:
#macro sgn(xx) (xx>0?1:(xx<0?-1:0)) #end
--
Mike Williams
Gentleman of Leisure
Post a reply to this message
|
![](/i/fill.gif) |