[REBOL] Re: How to check function arguments ?
From: carl:cybercraft at: 9-Jun-2002 10:07
On 09-Jun-02, Jason Cunliffe wrote:
> Hi Gregg
>> Do you mean refinements?
> ..not exactly thanks, but your example taught me something handy:-)
>>> somefunc: func [inp] [print [inp * 3.14159]]
>>> somefunc 4
> 12.56636
>>> somefunc
> ** Script Error: somefunc is missing its inp argument
> ** Near: somefunc
> Q1: How to catch the missing param so the script won't crash?
Hi Jason,
If it's just error trapping you want, then use "error? try". ie...
>> error? try [somefunc]
== true
>> error? try [somefunc wrong-input]
== true
>> error? try [somefunc wrong-input and-another-wrong-input]
== true
>> error? try [somefunc 3]
9.42477
== false
Though you shouldn't be using error-trapping to catch errors in the
script of course! (:
However, going by your first post I gathered you wanted a function to
work on an arbitrary number of arguments. I'm not sure if it can be
done in REBOL the way you are wanting, but the REBOL way to do it is
to supply the arguments in a block. 'join's a good example...
>> ? join
USAGE:
JOIN value rest
DESCRIPTION:
Concatenates values.
JOIN is a function value.
ARGUMENTS:
value -- Base value (Type: any)
rest -- Value or block of values (Type: any)
So...
>> join "a" "b"
== "ab"
>> join "a" ["b" "c" "d" "e"]
== "abcde"
Obviously that always requires two arguments with the second one being
optionally a block, but if it's zero or more arguments you're after,
just have a block with an empty one equating to no arguments. ie...
sum: func [numbers [number! block!] /local total][
if number? numbers [return numbers]
if empty? numbers [return none]
total: 0
forall numbers [total: total + numbers/1]
total
]
>> sum 1
== 1
>> sum [1]
== 1
>> sum [1 2]
== 3
>> sum [1 2 3]
== 6
And nothing in a block returns a none...
>> sum []
== none
Hope that helps.
--
Carl Read