(!****************************************************** Mosel User Guide Example Problems ================================= file uniondef.mos ````````````````` Defining unions. (c) 2021 Fair Isaac Corporation author: S. Heipcke, Mar. 2021 *******************************************************!) model "Defining unions" uses "mmsystem", "mmxprs" declarations u: string or real ! Scalar accepting 'string' or 'real' a,a1,a2,a3: any ! Entity accepting any type L: list of any ! List of type 'any' end-declarations ! Assigning a value determines the type of the union u:="a" writeln(u, " is string: ", u.typeid = string.id) ! Output: true u:=7,5 writeln(u, " is real: ", u.typeid = real.id) ! Output: true ! The preceding line is equivalent to: writeln(u, " is real: ", u is real) ! Output: true ! Assignment of basic types results in constants, all others are references a:=10 writeln(a, ":", a.struct=STRUCT_CONST, a is integer) ! Output: true true a:=date(2020,12,24) writeln(a, ":", a.struct=STRUCT_REF, a is date) ! Output: true true ! Can specify type in assignment to force a particular type a.real:=10 writeln(a, ":", a is real, a is integer) ! Output: true false a.text:="a text" writeln(a, ":", a is text, a is string) ! Output: true false ! Employ 'create' for types that do not support assignment such as 'mpvar': create(a.mpvar) writeln(getsol(a.mpvar), ":", a is mpvar) ! Output: true ! ... or to change the type without performing any assignment: create(a.linctr) writeln(getact(a.linctr), ":", a is linctr) ! Output: true !**** Defining a type name for a union of the 4 basic Mosel types declarations basictype = string or integer or real or boolean B: array(range) of basictype ! Array of union type 'basictype' end-declarations B(1):="abc"; B(3):=5; B(4):=5 forall(i in 1..3) writeln(B(i), ":", B(i) is string) ! Output: abc:true ?:false 5:false writeln(B(2).struct=STRUCT_NIL) ! Undefined entry has no structure writeln(B(2).typeid=STRUCT_NIL) ! Undefined entry has no type writeln(B(3)=B(4), B(3).integer=B(4).real) ! Output: false true !**** Wrapping mechanism for subroutines: compatible union types are accepted procedure dosomething(aunion: any) writeln("In procedure: ", aunion) end-procedure a:=date(2020,12,24) ! u:=7,5; B(1):="abc" dosomething(a) dosomething(u) dosomething(B(1)) dosomething(B(10)) ! Undefined entry procedure dosomething2(aunion: basictype) writeln("In procedure 2: ", aunion) end-procedure ! dosomething2(a) ! This would result in an error since 'date' is not a compatible type a:=1,5 ! u:=7,5; B(1):="abc" dosomething2(a) dosomething2(u) dosomething2(B(1)) end-model