Last active
August 29, 2015 14:03
-
-
Save mgdelacroix/dc20a05e0fc89f8c3a2b to your computer and use it in GitHub Desktop.
Either and fmap simple (and not formal) implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum EitherStatus { | |
LEFT, RIGHT | |
} | |
class Either { | |
EitherStatus status = EitherStatus.RIGHT | |
Map data | |
String toString() { | |
return "[${this.status}] > ${this.data}" | |
} | |
} | |
Closure printName = { Either either -> | |
if (either.data.firstName) { | |
println "First Name: ${either.data.firstName}" | |
return either | |
} else { | |
return [status: EitherStatus.LEFT, data: [error: 'First name not found']] as Either | |
} | |
} | |
Closure printLastName = { Either either -> | |
if (either.data.lastName) { | |
println "Last Name: ${either.data.lastName}" | |
return either | |
} else { | |
return ([status: EitherStatus.LEFT, data: [error: 'Last Name not found']] as Either) | |
} | |
} | |
Closure printFullName = { Either either -> | |
if (either.data.firstName && either.data.lastName) { | |
println "Full Name: ${either.data.firstName} ${either.data.lastName}" | |
return either | |
} else { | |
return ([status: EitherStatus.LEFT, data: [error: 'First or Last Name not found']] as Either) | |
} | |
} | |
Either bind(Either either, Closure... methods) { | |
for (Closure method : methods) { | |
if (either.status == EitherStatus.LEFT) { | |
break | |
} else { | |
either = method.call(either) | |
} | |
} | |
return either | |
} | |
Either either = [status: EitherStatus.RIGHT, data: [firstName: 'John', lastName: 'Doe']] as Either | |
Either result | |
result = bind(either, printName, printLastName, printFullName) | |
println "RESULT: $result" | |
println '\n------------------------------------------------------' | |
either.data.lastName = '' | |
result = bind(either, printName, printLastName, printFullName) | |
println "RESULT: $result" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment