Skip to content

Commit

Permalink
Step 10: Generic F-program
Browse files Browse the repository at this point in the history
  • Loading branch information
truizlop committed Jan 21, 2019
1 parent aebcf7d commit b0d6d89
Showing 1 changed file with 24 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,42 +26,43 @@ struct Statement {
let accounts: Int
}

class Program {
let getBank1Credentials: Option<String> = .some("MyUser_Password")
let moneyInPocket: Int = 20
class Program<F, MonadF> where MonadF: Monad, MonadF.F == F {
let monad: MonadF

func getBalanceBank1(credentials: String) -> Option<Account> {
return .some(Account(id: "a1", balance: 100))
init(monad: MonadF) {
self.monad = monad
}

let getBalanceBank2: Option<Int> = .some(80)

var b1: Option<Int> {
return Option<Any>.monad().flatMap(self.getBank1Credentials, { credentials in
Option<Any>.functor().map(self.getBalanceBank1(credentials: credentials), { acc in acc.balance }).fix()
}).fix()
var getBank1Credentials: Kind<F, String> {
return monad.pure("MyUser_Password")
}
let moneyInPocket: Int = 20

var b2: Option<Int> { return self.getBalanceBank2 }

var p: Option<Int> {
return Option<Any>.applicative().pure(moneyInPocket).fix()
func getBalanceBank1(credentials: String) -> Kind<F, Account> {
return self.monad.pure(Account(id: "a1", balance: 100))
}

var balance: Option<Int> {
let combinator = Option.semigroup(Int.sumSemigroup)
return combinator.combine(combinator.combine(b1, b2), p).fix()
var getBalanceBank2: Kind<F, Int> {
return self.monad.pure(80)
}

var statement: Option<Statement> {
return Option<Any>.applicative().map2(b1, b2) { x, y in
Statement(isRich: (x + y > 1000), accounts: 2) }.fix()
var balance: Kind<F, Int> {
return monad.binding(
{ self.getBank1Credentials },
{ credentials in self.monad.map(self.getBalanceBank1(credentials: credentials), { acc in acc.balance }) },
{ _, _ in self.getBalanceBank2 },
{ _, _, _ in self.monad.pure(self.moneyInPocket) },
{ _, b1, b2, p in self.monad.pure(b1 + b2 + p) }
)
}

func run() {
print(balance)
print(statement)
}
}

Program().run()
Program(monad: Id<Any>.monad()).run()
Program(monad: Option<Any>.monad()).run()
Program(monad: Either<String, Any>.monad()).run()
Program(monad: Try<Any>.monad()).run()
Program(monad: ListK<Any>.monad()).run()

0 comments on commit b0d6d89

Please sign in to comment.