|
Posted by Michael on March 9, 2008, 5:15 pm
Please log in for more thread options On Sun, 09 Mar 2008 18:56:51 +0100, Joost Diepenmaat wrote:
<snip>
>> Just as a matter of interest, so far as I could see, my technique of
>> setting a flag was the simplest way of maintaining the integrity of the
>> foreach (terminating it with "last" rather than jumping out of it with
>> "return"), whilst not wasting processor cycles performing irrelevant
>> loops later in the function. I am a newbie and don't know much - is
>> there a more elegant alternative which would satisfy the functional
>> programmers?
>
> There are more "elegant" (for some value of elegant) functional
> alternatives , but perl's constructs don't really allow you to write
> them as nicely as more functional programming languages do. For one,
> perl's if { ... } else { ... } constructs aren't expressions, and also,
> perl uses arrays instead of linked lists:
>
> example in common lisp
>
> (defun find-value (value list)
> (and list
> (if (string= value (first list))
> value
> (find-value (rest list)))))
>
> (defun example
> (or (find-value my-value my-list)
> (find-value my-other-value my-other-list)))
>
> Using these kind of recursive calls almost automatically force you to
> break up your sample problem into 2 subs.
>
> Also note that you can then re-use the find-value sub to reduce the
> total amount of code.
>
>
> same algorithm in perl.
>
> sub find_value {
> my ($value,@list) = @_;
> if (@list) {
> my $first = shift @list;
> if ($first eq $value) {
> return $first;
> }
> return find_value($value,@list);
> }
> return; # return false
> }
>
> sub example {
> find_value($value,@list) or
> find_value($other_value,@other_list);
> }
>
> note that you probably still want to use plenty of return()s here.
>
> also note: is is pretty inefficient if @list is long. you'd generally
> write the find_value function using foreach(), and pass the lists as
> array references.
>
> ps: none of this code has been tested. YMMV.
Thank-you very much for taking the time to write so helpfully Joost.
/M
|