Skip to content
Robert Peszek edited this page Sep 17, 2013 · 1 revision

If-Else Expressions:

Classic If-elseif-else force programmer into mutating state. Only if Groovy 'ifs' returned values like in SCALA or Haskell, life would be so much better! Fpiglet implements if-else DSL using composition of curried functions. (Curried Functions simplify DSL-like coding quite a bit). Here is an example with if-else chain:

import static fpig.expressions.IfElseSyntax.*

def score = 75.2
def grade =    _if_{ score > 89 } >> _then_ {'A'} >>
        _elseif_{ score > 79 } >> _then_ {'B'} >>
        _elseif_{ score > 69 } >> _then_ {'C'} >>
          _else_{ 'F' }
				
assert grade == 'C'

Or to get more FUNctional:

//shows lazy if statement chain, all evaluation is deferred to the time number is passed to grade function
def grade  = _ifun_{ it > 89 } >> _then_ {'A'}  >>
         _elseif_{ it > 79 } >> _then_ {'B'}  >>
         _elseif_{ it > 69 } >> _then_ {'C'}  >>
          _else_ { 'F' }
				
assert grade(75.2) == 'C'
assert grade(85.2) == 'B'
assert grade(90) == 'A'

Note: chaining in the reverse direction using << works with Fpiglet if-else chains too. This is maybe more explicit if you think of function composition, but else<<then<<elseif<<then<<if is a bit hard to read.

Localized Scope Expressions:

Next example shows Fpiglet DSL for coding with a very localized scope (yes implemented with curried function composition):

import static fpig.expressions.EvalWhereSyntax.*

def bmiCalculator = {massLb, heightIn -> (massLb / (heightIn * heightIn)) * 703}							
def littleGuyBmi = eval { bmi(littleguy) } <<
                where {
                  bmi = {person -> bmiCalculator(person.wLb, person.hIn)}
                  littleguy = [name:'littleguy', wLb: 150, hIn:5*12]
                }

Monadic Comprehensions:

Please see MonadicComprehensions.

Clone this wiki locally