RosettaCodeData/Task/Extend-your-language/PHL/extend-your-language.phl

54 lines
1.5 KiB
Plaintext

module stmts;
import phl::lang::io;
/* LinkedList --> Each element contains a condition */
struct @ConditionalChain {
field @Boolean cond;
field @ConditionalChain next;
@ConditionalChain init(@Boolean cond, @ConditionalChain next) [
this::cond = cond;
this::next = next;
return this;
]
/*
* If the condition is true executes the closure and returns a false element, otherwise returns the next condition
*
* Execution starts from the first element, and iterates until the right element is found.
*/
@ConditionalChain then(@Closure<@Void> closure) [
if (isNull(next())) return new @ConditionalChain.init(false, null);
if (cond()) {
closure();
return new @ConditionalChain.init(false, null);
}
else return next();
]
/* Operators create a cool look */
@ConditionalChain operator then(@Closure<@Void> closure) alias @ConditionalChain.then;
@ConditionalChain operator else1(@Closure<@Void> closure) alias @ConditionalChain.then;
@ConditionalChain operator else2(@Closure<@Void> closure) alias @ConditionalChain.then;
@ConditionalChain operator orElse(@Closure<@Void> closure) alias @ConditionalChain.then;
};
/* Returns linked list [a && b, a, b, true] */
@ConditionalChain if2(@Boolean a, @Boolean b) [
return new @ConditionalChain.init(a && b, new @ConditionalChain.init(a, new @ConditionalChain.init(b, new @ConditionalChain.init(true, null))));
]
@Void main [
if2(false, true) then [
println("Not this!");
] else1 [
println("Not this!");
] else2 [
println("This!");
] orElse [
println("Not this!");
];
]