Created
March 31, 2015 03:31
-
-
Save haskellcamargo/0d1acb3a36fd2da4f0e9 to your computer and use it in GitHub Desktop.
Maybe Monad AdvPL
This file contains hidden or 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
#include "prelude.ch" | |
#include "protheus.ch" | |
/** | |
* Monadic implementation for AdvPL | |
* @author Marcelo Camargo | |
*/ | |
Class Maybe From Monad | |
Method New( xVal ) Constructor | |
Method Bind( bFun ) | |
Method IsNothing() | |
Method Maybe( xDefault, bFun ) | |
EndClass | |
// Nothing | |
Class Nothing From Maybe | |
Method New() Constructor | |
EndClass | |
Method New() Class Nothing | |
Return Nil | |
Method Bind( _ ) Class Nothing | |
Return Self | |
Method IsNothing() Class Nothing | |
Return .T. | |
Method Val() Class Nothing | |
Throw "Cannot call Val() of Nothing." | |
Method Maybe( xDefault, _ ) Class Nothing | |
Return xDefault | |
// Just t | |
Class Just From Maybe | |
Data xValue | |
EndClass | |
Method New( xVal ) Class Maybe | |
If Type( xVal ) == 'U' .Or. xVal == Nil | |
Return Nothing():New() | |
EndIf | |
Return Just():New( xVal ) | |
Method New( xVal ) Class Just | |
::xValue := xVal | |
Return Self | |
Method Bind( bFun ) Class Just | |
Return Maybe():New( Eval( bFun, ::xValue ) ) | |
Method IsNothing() Class Just | |
Return .F. | |
Method Val() Class Just | |
Return ::xValue | |
Method Maybe( _, bFun ) Class Just | |
Return Eval( bFun, ::xValue ) | |
nTest := Maybe():New( 10 ) | |
nTest:Bind(Fun ( N ) -> ; | |
N * 2 ; | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment