Instead of defining functions in a loop, you can write a function that
defines a function, and call this for all letters:

makefun(letter) = @eval function $letter(T::test) T.$letter end
makefun(:A)
makefun(:B)

This makes it easier to pass additional arguments to makefun if necessary,
e.g. if there are slight (but somewhat inconsistent) differences between
the functions.

-erik


On Wed, Sep 2, 2015 at 6:21 AM, Robert DJ <[email protected]> wrote:

> Wow! It *was* really simple!
>
> Thanks a lot -- also for the blog post.
>
>
> On Wednesday, September 2, 2015 at 11:56:13 AM UTC+2, Simon Danisch wrote:
>>
>> this case is pretty simple:
>> for letter in [:A,:B]
>>      @eval begin
>>         function $letter(T::test)
>>                 T.$letter
>>         end
>>      end
>> end
>> @eval == eval(quote .... end) == eval( :( .... ) )
>> Am Mittwoch, 2. September 2015 11:16:53 UTC+2 schrieb Robert DJ:
>>>
>>> Hi,
>>>
>>> I have a situation where a number of functions differ so little that it
>>> would make sense to define them by a loop.
>>> I don't know if I am using the correct jargon, but here is a small
>>> example to illustrate:
>>>
>>> type test
>>>         A::Int
>>>         B::Int
>>> end
>>>
>>> function A(T::test)
>>>         T.A
>>> end
>>>
>>> function B(T::test)
>>>         T.B
>>> end
>>>
>>>
>>> If possible, I would like to define the functions A and B along these
>>> lines:
>>>
>>> for letter in [A,B]
>>>         function letter(T::Test)
>>>                 T.letter
>>>         end
>>> end
>>>
>>>
>>> Thanks,
>>>
>>> Robert
>>>
>>


-- 
Erik Schnetter <[email protected]>
http://www.perimeterinstitute.ca/personal/eschnetter/

Reply via email to