Ladislav asked for some functional programming in REBOL, so I've
come up with a challenge.

Using only functional programming, perform these tasks:

1.  Compute the product of the first 10 odd numbers.
    (answer is 654729075)

2.  Compute the sum of the primes less than 100.
    (answer is 1060)

3.  Return a block of the strings present in this structure:
    [[[3 "hello"] [6 "world"] [7 "from" "rebol" 21]]
     [[["hi"] ["this" ['aword] "is"] "a"] "test"]]

    (answer is ["hello" "world" "from" "rebol" "hi" "this"
                "is" "a" "test"])

As it turns out, it isn't possible to do this in REBOL with
purely functional code because there doesn't seem to be a way
to prepend an element to a block in a non-destructive way.
However, if we cheat a little and introduce these functions:

prepend: func [item blk] [
    result: make block! (length? blk) + 1
    insert result item
    insert next result blk
    return result
    ]

ndappend: func [b1 b2] [
    result: make block! (length? b1) + (length? b2)
    insert insert result b1 b2
    return result
    ]

We can do the problems in a purely functional manner.
Although it is possible to write a FILTER function in a purely
functional manner (provided you use prepend), it comes out
being an O(n^2) algorithm due to the nature of REBOL blocks.
This imperative version is much more efficient.

filter: func [f blk][
    result: make block! (length? blk)
    foreach element blk [
        if f element [result: insert result element]
        ]
    return head result
]

I'll let you think about this for a little while and post my solutions
later today.

------
You can ignore this section if you are tired of my ranting.

To support my claim that REBOL encourages imperative programming
over functional, note that REBOL/core doesn't provide a way of
prepending an element to a block without side effects.  I had to
use imperative programming to write it, but notice that it is of O(n)
in time and space usage whereas it is O(1) in most functional
languages.  This causes the functional version of filter to be
O(n^2), so again we cheat and use imperative programming because
it is more efficient in REBOL.


______________________________________________________
Get Your Private, Free Email at http://www.hotmail.com

Reply via email to