MENU
Contact
Contact

Automatic parallelization of for-comprehensions in Scala 3

Picture of Kacper Korban, Scala Developer @ Scala 3

Kacper Korban

Scala Developer @ Scala 3
Nov 22, 2022|12 min read
Image Alt
1productService.getInfo: ProductID => IO[ProductInfo]
2userService.getInfo: UserID => IO[UserInfo]
3recommendationService.getSimilarProducts: ProductID => IO[List[ProductID]]
4ratingService.getUserRating: UserID => IO[Int]
5renderingService.renderProductSite: ProductInfo => UserInfo => List[ProductID] => Int => HTML
1def renderProductSiteSigma(productID: ProductID): IO[HTML] =
2 productService.getInfo(productID).flatMap { product =>
3 recommendationService.getSimilarProducts(productID).flatMap { recommended =>
4 userService.getInfo(product.ownerID).flatMap { owner =>
5 ratingService.getUserRating(product.ownerID).map { rating =>
6 renderingService.renderProductSite(product, owner, recommended, rating)
7 }
8 }
9 }
10 }
1def renderProductSiteSigmaPar(productID: ProductID): IO[HTML] =
2 productService.getInfo(productID)
3 .zipPar(recommendationService.getSimilarProducts(productID))
4 .flatMap { case (product, recommended) =>
5 userService.getInfo(product.ownerID)
6 .zipPar(ratingService.getUserRating(product.ownerID))
7 .map { case (owner, rating) =>
8 renderingService.renderProductSite(product, owner, recommended, rating)
9 }
10 }
1def renderProductSiteBetaPar(productID: ProductID): IO[HTML] =
2 for {
3 (product, recommended) <- productService.getInfo(productID)
4 .zipPar(recommendationService.getSimilarProducts(productID))
5 (owner, rating) <- userService.getInfo(product.ownerID)
6 .zipPar(ratingService.getUserRating(product.ownerID))
7 } yield renderingService.renderProductSite(product, owner, recommended, rating)
1import avocado.*
2import avocado.instances.your_effect_system.given
3
4def renderProductSiteBetaParAcocADO(productID: ProductID): IO[HTML] =
5 ado {
6 for {
7 product <- productService.getInfo(productID)
8 recommended <- recommendationService.getSimilarProducts(productID)
9 owner <- userService.getInfo(product.ownerID)
10 rating <- ratingService.getUserRating(product.ownerID)
11 } yield renderingService.renderProductSite(product, owner, recommended, rating)
12 }

Scala 3 support subscription

Subscribe to our newsletter and never miss an article