Created
          November 22, 2017 22:34 
        
      - 
      
- 
        Save RPallas92/aa0de821a0eb0d0f14d7bbe1f4f57042 to your computer and use it in GitHub Desktop. 
    facile-it/Monads test
  
        
  
    
      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
    
  
  
    
  | import Monads | |
| func test() { | |
| typealias DeferredResult<T> = Deferred<Result<T, String>> | |
| typealias AsyncResult<T> = Effect<DeferredResult<T>> | |
| struct User { | |
| var name: String | |
| var dateOfBirth: String | |
| } | |
| struct UserRepository { | |
| let user1 = User(name: "Ricardo", dateOfBirth: "01/05/1992") | |
| func getUserByName(name: String) -> AsyncResult<User> { | |
| return AsyncResult<User>.init { () -> Deferred<Result<User, String>> in | |
| return DeferredResult.init(completion: { (completion) in | |
| print("Inside async result") | |
| if(name == "Ricardo"){ | |
| //Async: Simulates retrieving the user from DB | |
| DispatchQueue.main.async { | |
| completion(Result.success(self.user1)) | |
| } | |
| } else { | |
| //Async: Simulates trying to retrieve the user from DB | |
| DispatchQueue.main.async { | |
| print("inside async result's async queue") | |
| completion(Result.failure("User not exists")) | |
| } | |
| } | |
| }) | |
| } | |
| } | |
| } | |
| let userRepository = UserRepository() | |
| print("BEFORE CREATING async result") | |
| let userAsyncResult = userRepository.getUserByName(name: "Ricardo") | |
| print("AFTER CREATING async result") | |
| let upperCasedAsyncResult = userAsyncResult.mapTT { (user) -> User in | |
| let resultUser = User(name: user.name.uppercased(), dateOfBirth: user.dateOfBirth) | |
| return resultUser | |
| } | |
| //Impure part: Execute side effects | |
| let deferredResult = upperCasedAsyncResult.run() | |
| deferredResult.run { (userResult) in | |
| userResult.run( | |
| ifSuccess: {printUser($0)}, | |
| ifFailure: {print($0)}, | |
| ifCancel: {print("cancelled")}) | |
| } | |
| func printUser(_ user: User) -> () { | |
| print(user.name) | |
| } | |
| } | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Wrapping in
Effectis actually a very interesting strategy to add lazyness to basically everything :DIn FunctionalKit we're making
Future(ex-Deferred) lazy by default.