Sat Aug 18, 2018 2:28 pm
Login Register Lost Password? Contact Us


Returning multiple values from a function

Share ideas, code, best practices and techniques with other community members

Wed Oct 22, 2014 2:08 pm Change Time Zone

I just learned something today that is really neat and elegant. If you need to return multiple values from a function, simply wrap the values in a MODULE and make each value an exported attribute, then return the module.

Here is an example, which is the code from Std.Date.ToGregorianYMD() in the 5.0.0 version of the standard library:

Code: Select all
EXPORT ToGregorianYMD(Days_t days) := FUNCTION
    //See Fliegel and van Flandern (1968) and other quoted sources (e.g., http://www.ortelius.de/kalender/calc_en.php)
    //Process as 4, 100 and 400 year cycles.
    daysIn4Years := 3*365+366;
    daysIn100Years := 25*daysIn4Years-1;
    daysIn400Years := 4*daysIn100Years+1;

    //Calulate days in each of the cycles.
    adjustedDays := days - GregorianDateOrigin;
    num400Years := adjustedDays div daysIn400Years;
    rem400Years := adjustedDays % daysIn400Years;

    num100Years := ((rem400Years div daysIn100Years + 1) * 3) DIV 4;
    rem100Years := rem400Years - num100Years * daysIn100Years;

    num4Years := rem100Years div daysIn4Years;
    rem4Years := rem100Years % daysIn4Years;

    years := ((rem4Years div 365 + 1) * 3) DIV 4;
    numdays := rem4Years - years * 365;

    //Now calculate the actual year, month day
    y := num400Years * 400 + num100Years * 100 + num4Years * 4 + years;
    m := (numdays * 5 + 308) div 153 - 2;
    d := numdays - (m + 4) * 153 div 5 + 122;
    result := MODULE
        EXPORT year := (y + (m + 2) div 12) - YearDelta;
        EXPORT month := (m + 2) % 12 + 1;
        EXPORT day := d + 1;
    END;
    return result;
END;

The example from the documentation illustrates how you use this:

Code: Select all
IMPORT STD;
INTEGER2  MyYear  := 2012;
UNSIGNED1 MyMonth := 1;
UNSIGNED1 MyDay   := 1;
J := STD.Date.FromGregorianYMD(MyYear,MyMonth,MyDay);
    //J contains 734503
Y := STD.Date.ToGregorianYMD(J).Year;   //Y contains 2012
M := STD.Date.ToGregorianYMD(J).Month;  //M contains 1
D := STD.Date.ToGregorianYMD(J).Day;    //D contains 1

Pretty neat.

Cheers,

Dan
DSC
Community Advisory Board Member
Community Advisory Board Member
 
Posts: 552
Joined: Tue Oct 18, 2011 4:45 pm

Wed Oct 22, 2014 2:13 pm Change Time Zone

Dan,

Thanks for bringing this up. It's one of those "little" things in ECL that can easily get overlooked, but can be quite useful. :)

Richard
rtaylor
Community Advisory Board Member
Community Advisory Board Member
 
Posts: 1370
Joined: Wed Oct 26, 2011 7:40 pm


Return to Tips & Tricks

Who is online

Users browsing this forum: No registered users and 1 guest

cron