Accumulator factory: Difference between revisions

no edit summary
m (Automated syntax highlighting fixup (second round - minor fixes))
No edit summary
Line 1,035:
 
Randomized with seed 587000
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
in Org:RosettaCode
^|EMal has a mechanism to force the type system to allow nulls on types
|that are usually not nullable, such as int or real.
|In the following code we are telling EMal that int and real implement
|the Number virtual interface, so that it can only accept: null, int, and real values.
|^
type Number nulls int, real
type AccumulatorUsingNumber
fun foo = fun by Number n
fun g = Number by Number i
return n += i
end
return g
end
type AccumulatorUsingVar
^|EMal has an universal supertype Variable (var) that can be used.
|Some manual type checks are required.
|^
fun checkType = void by var value
if generic!value != real and generic!value != int
Event.error(1, "Only real and int values can be used").raise()
end
end
fun foo = fun by var n
checkType(n)
fun g = var by var i
checkType(i)
return n += i
end
return g
end
type Main
^|we have developed two solutions,
|it's time to create a list holding both data types.
|We iterate over the solutions in order to test them.
|^
List solutions = generic[AccumulatorUsingNumber, AccumulatorUsingVar]
for int i = 0; i < 2; ++i
generic solution = solutions[i]
writeLine("=== solution: " + (i + 1) + " ===")
fun x = :solution.foo(1)
x(5)
:solution.foo(3)
watch(x(2.3))
fun y = :solution.foo(1)
y(5)
:solution.foo(3)
watch(y(2))
end
</syntaxhighlight>
{{out}}
<pre>
=== solution: 1 ===
Org:RosettaCode:Number, Real: <8.3>
Org:RosettaCode:Number, Integer: <8>
=== solution: 2 ===
Variable, Real: <8.3>
Variable, Integer: <8>
</pre>
 
214

edits