Skip to content

Instantly share code, notes, and snippets.

@hlindberg
Created October 5, 2018 09:32
Show Gist options
  • Save hlindberg/839a228f98e61603dc703d945f0177a1 to your computer and use it in GitHub Desktop.
Save hlindberg/839a228f98e61603dc703d945f0177a1 to your computer and use it in GitHub Desktop.
A fun example using Deferred to write puppet code in a functional style
# Resolves a given value - if given a Deferred it will be called and all other values are returned as is.
#
function resolve(Any $x) {
if $x =~ Deferred { $x.call } else { $x }
}
# Resolves and evaluates a condition and either resolves and evaluates the given when_true,
# or the given when_false depending on the outcome of the evaluation of the condition.
# The result is undef if the selected when_true/when_false is undefined.
#
function if_true(
Any $test,
Optional[Any] $when_true = undef,
Optional[Any] $when_false = undef
) {
if resolve($test) { resolve($when_true) }
else { resolve($when_false) }
}
# Example function
function do_this() {
notice "Doing this"
}
# Example function
function do_that() {
notice "Doing that"
}
# Example - using the if_true() function (notices "Doing that")
false.if_true(Deferred('do_this'), Deferred('do_that'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment