tags:

views:

62

answers:

3

How can I refer to date as argument in f within the foreach loop if date is also used as block element var ? Am I obliged to rename my date var ?

f: func[data [block!] date [date!]][
    foreach [date o h l c v] data [

    ]
]
+2  A: 

You need to either change the parameter name from date or assign it to a local variable.

Graham Chiu
+2  A: 

You can access the date argument inside the foreach loop by binding the 'date word from the function specification to the data argument:

>> f: func[data [block!] date [date!]][
[    foreach [date o h l c v] data [     
[        print last reduce bind find first :f 'date 'data
[        print date
[        ]
[    ]

>> f [1-1-10 1 2 3 4 5 2-1-10  1 2 3 4 5] 8-9-10
8-Sep-2010
1-Jan-2010
8-Sep-2010
2-Jan-2010

It makes the code very difficult to read though. I think it would be better to assign the date argument to a local variable inside the function as Graham suggested.

>> f: func [data [block!] date [date!] /local the-date ][
[    the-date: :date                                       
[    foreach [date o h l c v] data [                       
[        print the-date                                        
[        print date                                            
[        ]
[    ]
>> f [1-1-10 1 2 3 4 5 2-1-10  1 2 3 4 5] 8-9-10         
8-Sep-2010
1-Jan-2010
8-Sep-2010
2-Jan-2010
Peter W A Wood
The technique of binding an additional argument to a block would be more difficult to apply if the foreach loop was iterating over the elements of the block one at a time. There would probably be an additional iteration for the date.
Peter W A Wood
+4  A: 

A: simple, compose is your best friend.

f: func[data [block!] date [date!]][
    foreach [date str] data compose [
        print (date)
        print date
    ]
]

>> f [2010-09-01 "first of sept" 2010-10-01 "first of october"] now

7-Sep-2010/21:19:05-4:00
1-Sep-2010
7-Sep-2010/21:19:05-4:00
1-Oct-2010
moliad
obviously, all parens are replaced, so in some situations the above is either impossible or unwieldy, but in the vast majority of cases, it works.
moliad
Ah, this is a clever answer!!
Hostile Fork