[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQProvectus
Взглянем на Coq с точки зрения программиста, а не математика, и посмотрим какие в нём есть средства не только для усложнения, но и облегчения написания функционального кода
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQProvectus
Взглянем на Coq с точки зрения программиста, а не математика, и посмотрим какие в нём есть средства не только для усложнения, но и облегчения написания функционального кода
Expressing Types as values using GADTS in scala and various other techniques. Using Schemas in this style allows subsequent derivation ot Typeclass instances (and other fun things)
If you want to play around with a minimal example of the involved code here you go: https://scalafiddle.io/sf/YSrSwQy/1
Introduction to Functional Programming with ScalaDaniel Cukier
Scala é uma linguagem funcional que roda na JVM. Ela possui todas as vantagens da programação funcional, com a vantagem de ser facilmente integrada com Java, além de possuir uma stack completa de desenvolvimento e deploy. Nessa palestra, daremos os primeiros passos para quem quer trabalhar com Scala. Falaremos de imutabilidade, Traits, funções e expressões lambda entre outros tópicos
Scalaz 8 is the latest edition of the popular functional programming library for Scala. In this whirlwind tour, maintainer John A. De Goes discusses some of the hottest features of Scalaz 8, including all of the following:
* A fast, concurrent, and leak-free effect system, which has small, composable, and powerful primitives for building practical, real-world software;
* A non-linear type class hierarchy, which permits a more powerful hierarchy that infers well without devastating ambiguous implicit errors;
* A new encoding for abstractions in category theory that providers higher fidelity and enables new categories of useful software to be developed;
* A Scala 2.12 encoding of opaque types that powers improved performance and better developer UX.
In this tour, you’ll see how the design of Scalaz 8 was inspired by a desire to provide Scala developers with a principled, performant, and pragmatic library that never sacrifices the safety and equational reasoning properties of functional programming. You’ll see live code snippets that show you how solving complex real world problems is simpler, faster, safer, and more reasonable than in previous versions of Scalaz. And hopefully you’ll be inspired at just how far functional programming in Scala has come in the past decade.
Scala en proyectos de vinculación Ancap-UR - 2013-03Germán Ferrari
Diapositivas de una presentación que di para la Scala Meetup Montevideo el 21 de marzo de 2013, para compartir la experiencia de uso de Scala como parte de mi trabajo en proyectos de vinculación entre ANCAP y la Universidad de la República.
Scala - The Simple Parts, SFScala presentationMartin Odersky
These are the slides of the talk I gave on May 22, 2014 to the San Francisco Scala user group. Similar talks were given before at GOTO Chicago, keynote, at Gilt Groupe and Hunter College in New York, at JAX Mainz and at FlatMap Oslo.
Expressing Types as values using GADTS in scala and various other techniques. Using Schemas in this style allows subsequent derivation ot Typeclass instances (and other fun things)
If you want to play around with a minimal example of the involved code here you go: https://scalafiddle.io/sf/YSrSwQy/1
Introduction to Functional Programming with ScalaDaniel Cukier
Scala é uma linguagem funcional que roda na JVM. Ela possui todas as vantagens da programação funcional, com a vantagem de ser facilmente integrada com Java, além de possuir uma stack completa de desenvolvimento e deploy. Nessa palestra, daremos os primeiros passos para quem quer trabalhar com Scala. Falaremos de imutabilidade, Traits, funções e expressões lambda entre outros tópicos
Scalaz 8 is the latest edition of the popular functional programming library for Scala. In this whirlwind tour, maintainer John A. De Goes discusses some of the hottest features of Scalaz 8, including all of the following:
* A fast, concurrent, and leak-free effect system, which has small, composable, and powerful primitives for building practical, real-world software;
* A non-linear type class hierarchy, which permits a more powerful hierarchy that infers well without devastating ambiguous implicit errors;
* A new encoding for abstractions in category theory that providers higher fidelity and enables new categories of useful software to be developed;
* A Scala 2.12 encoding of opaque types that powers improved performance and better developer UX.
In this tour, you’ll see how the design of Scalaz 8 was inspired by a desire to provide Scala developers with a principled, performant, and pragmatic library that never sacrifices the safety and equational reasoning properties of functional programming. You’ll see live code snippets that show you how solving complex real world problems is simpler, faster, safer, and more reasonable than in previous versions of Scalaz. And hopefully you’ll be inspired at just how far functional programming in Scala has come in the past decade.
Scala en proyectos de vinculación Ancap-UR - 2013-03Germán Ferrari
Diapositivas de una presentación que di para la Scala Meetup Montevideo el 21 de marzo de 2013, para compartir la experiencia de uso de Scala como parte de mi trabajo en proyectos de vinculación entre ANCAP y la Universidad de la República.
Scala - The Simple Parts, SFScala presentationMartin Odersky
These are the slides of the talk I gave on May 22, 2014 to the San Francisco Scala user group. Similar talks were given before at GOTO Chicago, keynote, at Gilt Groupe and Hunter College in New York, at JAX Mainz and at FlatMap Oslo.
Leveraging Scala Macros for Better ValidationTomer Gabel
A talk given at Scalapeño 2014 and JavaOne 2014 (video links to follow).
Data validation is a common enough problem that numerous attempts have been made to solve it elegantly. The de-facto solution in Java (JSR 303) has a number of shortcomings and fails to leverage the powerful Scala type system. The release of Scala 2.10.x introduced a couple of experimental metaprogramming features, namely reflection and macros. In this talk I'll introduce macros by way of a practical example: implementing a full-blown data validation engine, utilizing def macros and a Scala DSL to enable elegant validator definition syntax and call-site.
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala, and others (Martin Odersky, Derek Wyatt, Adelbert Chang)
Lazy Java by Mario Fusco
Like all imperative languages Java is, with some minor but notable exceptions, an eagerly evaluated programming language. Nevertheless the introduction of lambdas in Java 8 also allowed the adoption of some lazy patterns and data structures that are more typically employed in functional languages. Streams represent the most evident example of how also native Java API has taken advantage of laziness, but there is a number of other interesting scenarios where laziness can be an effective solution to quite common problems. In fact laziness is the only possible technique to process potentially infinite amount of data, or more in general to delay the expensive evaluation of an expression only when and if it is necessary. But laziness is even more than that: for instance the reader monad delays not only a computation but also the need of external dependencies thus lowering the abuse of dependency injection, while a trampoline uses laziness to delay and then linearize recursive calls preventing the overflow of the stack. The purpose of this talk is illustrating why and how implementing laziness in Java with practical examples delivered with both slides and live coding sessions.
Mario Fusco - Lazy Java - Codemotion Milan 2018Codemotion
Like all imperative languages Java is eagerly evaluated, but the introduction of lambdas allowed the adoption of some lazy patterns and data structures that are typically functional. Streams are the most evident example of a native Java API using laziness, but there are other cases where laziness is an effective solution to common problems. In fact it makes possible to process infinite amount of data, but it is even more than that. This talk shows why and how implementing laziness in Java with practical examples delivered with both slides and live coding sessions.
Watch video (in Hebrew): http://parleys.com/play/53f7a9cce4b06208c7b7ca1e
Type classes are a fundamental feature of Scala, which allows you to layer new functionality on top of existing types externally, i.e. without modifying or recompiling existing code. When combined with implicits, this is a truly remarkable tool that enables many of the advanced features offered by the Scala library ecosystem. In this talk we'll go back to basics: how type classes are defined and encoded, and cover several prominent use cases.
A talk given at the Underscore meetup on 19 August, 2014.
This presentation explains few features of advance scala. The topics I have covered here are the Implementations of extractors, Implicit conversions, parameters and implicit context and update function with the code snippet.
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
The programming world is moving towards functional programming. All the major and popular programming languages (including Java, C++, C#, Swift, and Python) support functional programming. Functional programming languages such as Clojure, Scala, and F# are on the rise. This talk introduces functional programming to those who are new to this paradigm using lambda functions in Java 8. The talk will cover syntax and semantics of lambda functions, moving from external iteration to internal iteration, and how lambda functions can result in shorter and more readable code. If you are new to functional programming and want productivity gains from using Java’s lambda functions, this talk is certainly for you.
A teaser talk for Scala newbies, introducing five basic elements that (in my opinion) make the transition from Java to Scala a no-brainer.
Given at the 7th JJTV (Israeli Java/JVM user group) tool night, July 2nd, 2013.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
6. optional
AND YOUR MAIN METHOD WILL BE INVOKED SUCH THAT:
count = Some(5)
file = None
arg1 = quux
7. optional
AND YOUR MAIN METHOD WILL BE INVOKED SUCH THAT:
count = Some(5)
file = None
arg1 = quux
object MyAwesomeCommandLineTool extends optional.Application {
// for instance...
def main(count: Option[Int], file: Option[java.io.File],
arg1: String) {
[...]
}
}
scala MyAwesomeCommandLineTool --count 5 quux
Ref by name
8. optional
AND YOUR MAIN METHOD WILL BE INVOKED SUCH THAT:
count = Some(5)
file = None
arg1 = quux
object MyAwesomeCommandLineTool extends optional.Application {
// for instance...
def main(count: Option[Int], file: Option[java.io.File],
arg1: String) {
[...]
}
}
scala MyAwesomeCommandLineTool --count 5 quux
Ref by name
Optional parameter
9. optional
AND YOUR MAIN METHOD WILL BE INVOKED SUCH THAT:
count = Some(5)
file = None
arg1 = quux
object MyAwesomeCommandLineTool extends optional.Application {
// for instance...
def main(count: Option[Int], file: Option[java.io.File],
arg1: String) {
[...]
}
}
scala MyAwesomeCommandLineTool --count 5 quux
Ref by name
Optional parameter
Ref by position
14. So...
… copy the idea, but use Scala reflection
instead …
… and don’t worry and be crappy :) ...
15. Show me the code!
trait Application {
def main(args: Array[String]) {
runMain(this, args.toList)
}
private def runMain[T: ClassTag](
instance: T, args: List[String]) {
// ... something happens here ...
}
}
16. Show me the code!
private def runMain[T: ClassTag](instance: T, args: List[String]) {
val instanceMirror = ru.runtimeMirror(getClass.getClassLoader).reflect(instance)
val theType = instanceMirror.symbol.typeSignature
val methods = theType.members.collect {
case m if m.isMethod => m.asMethod
}
val mainMethods = methods.filter(m => m.name == ru.TermName("main") &&
m.fullName != classOf[Application].getName + ".main")
val methodOrError = mainMethods.headOption.toRight("No main method defined")
// Scala support multiple parameter lists, I care only about the first (if exists ...)
val = methodOrError.right.map(m => m.paramLists.headOption.getOrElse(Nil))
paramsOrError
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right // mysterious instantiation of things ...
} yield {
val refMethod = instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*) // here is the execution of the main method happening
}
invocationOrError.fold(println, identity /* nothing to do because it already executed as a side effect */)
}
17. Step by step: method definition
Scala method:
private def runMain[T: ClassTag](
instance: T, args: List[String]) {
private, so it’s not inherited
with a type parameter T
with a context bound ClassTag
18. Step by step: method definition
… with a context bound ClassTag?
private def runMain[T: ClassTag](
instance: T, args: List[String]) {
≡
private def runMain[T](
instance: T, args: List[String])(
implicit ev: ClassTag[T]) {
both expressions are analogous
19. Step by step: method definition
we ask for an evidence that a ClassTag can
be constructed for the type T ...
… so we can use runtime reflection on it ...
20. Step by step: reflecting on instance
val instanceMirror =
ru
.runtimeMirror(getClass.getClassLoader)
.reflect(instance)
21. Step by step: reflecting on instance
val instanceMirror =
ru
.runtimeMirror(getClass.getClassLoader)
.reflect(instance)
(mystic voice)
…You need a mirror to access the reflection…
22. Step by step: reflecting on instance
val instanceMirror =
ru
.runtimeMirror(getClass.getClassLoader)
.reflect(instance)
`ru` here is just an alias to package
scala.reflect.runtime.universe
import scala.reflect.runtime.{ universe => ru }
23. Step by step: reflecting on instance
val instanceMirror =
ru
.runtimeMirror(getClass.getClassLoader)
.reflect(instance)
A ClassTag is needed here to overcome the
erasure of the type at runtime T
24. Step by step: obtaining the method
I want the methods ...
val theType =
instanceMirror.symbol.typeSignature
val methods = theType.members.collect {
case m if m.isMethod => m.asMethod
}
25. Step by step: obtaining the method
… to get the right main methods ...
val mainMethods =
methods.filter(m =>
m.name == ru.TermName("main") &&
m.fullName !=
classOf[Application].getName + ".main")
26. Step by step: obtaining the method
… to get the right main methods ...
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
Give me either the first of the methods, if there
is one, or an error message
27. Step by step: obtaining the method
… to get the right main methods ...
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
Give me either the first of the methods, if there
is one, or an error message
28. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
Give me either the first of the methods, if there
is one, or an error message
29. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
headOption ~ List[A] => Option[A]
30. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
headOption ~ List[A] => Option[A]
Option[A] =
Some(a: A)
| None
31. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
headOption ~ List[A] => Option[A]
not scala (!)
Option[A] =
Some(a: A)
| None
32. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
headOption ~ List[A] => Option[A]
def headOption: Option[A] =
if (isEmpty) None else Some(head)
Option[A] =
Some(a: A)
| None
33. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
toRight[X] ~ Option[A] => (=> X) => Either[X,A]
34. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
toRight[X] ~ Option[A] => (=> X) => Either[X,A]
Either[A, B] =
Left(a: A)
| Right(b: B)
35. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
toRight[X] ~ Option[A] => (=> X) => Either[X,A]
def toRight[X](left: => X): Either[X,A] =
if (isEmpty) Left(left) else Right(this.get)
Either[A, B] =
Left(a: A)
| Right(b: B)
36. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
toRight[X] ~ Option[A] => (=> X) => Either[X,A]
def toRight[X](left: => X): Either[X,A] =
if (isEmpty) Left(left) else Right(this.get)
Either[A, B] =
Left(a: A)
| Right(b: B)
Either[String, ru.MethodSymbol]
37. Step by step: obtaining the method
… to get the right main methods …
val methodOrError =
mainMethods
.headOption
.toRight("No main method defined")
toRight[X] ~ Option[A] => (=> X) => Either[X,A]
def toRight[X](left: => X): Either[X,A] =
if (isEmpty) Left(left) else Right(this.get)
Either[A, B] =
Left(a: A)
| Right(b: B)
Either[String, ru.MethodSymbol]
38. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
Scala support multiple parameter lists.
I care only about the first (if exists …)
39. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
Either[String, ru.MethodSymbol]
40. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
Either[String, ru.MethodSymbol]
only the right part please
41. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
map[X] ~ Either[A,B] => (B => X) => Either[A,X]
Either[String, ru.MethodSymbol]
only the right part please
42. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
map[X] ~ Either[A,B] => (B => X) => Either[A,X]
def map[X](f: B => X) = e match {
case Left(a) => Left(a)
case Right(b) => Right(f(b))
}
Either[String, ru.MethodSymbol]
only the right part please
43. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
List[List[ru.Symbol]]
44. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
Option[List[ru.Symbol]]
List[List[ru.Symbol]]
45. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
f: ru.MethodSymbol => List[ru.Symbol]
46. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
f: ru.MethodSymbol => List[ru.Symbol]
paramsOrError: Either[String, List[ru.Symbol]]
47. Step by step: obtaining the params
Ok. Now I need the parameters:
val paramsOrError =
methodOrError.right.map(m =>
m.paramLists
.headOption.getOrElse(Nil))
f: ru.MethodSymbol => List[ru.Symbol]
paramsOrError: Either[String, List[ru.Symbol]]
paramsOrError have the parameters OR the
original error "No main method defined"
48. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
49. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
Same as before
50. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
Same as before
The main method if all is right
51. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
Same as before
The parameters if all is right
52. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
Same as before
The values to use to invoke
the method
53. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
Same as before
The values to use to invoke
the method if all is right :-)
54. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
Will compute only if all OK
55. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
Either[String, Any]
56. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
Either[String, Any]
The first error that occurs (if any)
57. Step by step: invocation
val invocationOrError =
for {
method <- methodOrError.right
params <- paramsOrError.right
values <- instantiate(params, args).right
} yield {
val refMethod =
instanceMirror.reflectMethod(method)
refMethod(values.unzip._2: _*)
}
Either[String, Any]
The first error that occurs (if any)
The value
returned by the
method (if all OK)
58. Step by step: handling ending cases
invocationOrError.fold(println, identity)
59. Step by step: handling ending cases
invocationOrError.fold(println, identity)
fold[X] ~
Either[A, B] => (A => X) => (B => X) => X
60. Step by step: handling ending cases
invocationOrError.fold(println, identity)
fold[X] ~
Either[A, B] => (A => X) => (B => X) => X
If you can convert the value at the left to X, and
the value at the right to X, then you can convert
an Either[A,B] to X
61. Step by step: handling ending cases
invocationOrError.fold(println, identity)
fold[X] ~
Either[A, B] => (A => X) => (B => X) => X
If you can convert the value at the left to X, and
the value at the right to X, then you can convert
an Either[A,B] to X
62. Step by step: handling ending cases
invocationOrError.fold(println, identity)
fold[X] ~
Either[A, B] => (A => X) => (B => X) => X
If you can convert the value at the left to X, and
the value at the right to X, then you can convert
an Either[A,B] to X
63. Step by step: handling ending cases
invocationOrError.fold(println, identity)
fold[X] ~
Either[A, B] => (A => X) => (B => X) => X
If you can convert the value at the left to X, and
the value at the right to X, then you can convert
an Either[A,B] to X
64. Step by step: handling ending cases
invocationOrError.fold(println, identity)
fold[X] ~
Either[A, B] => (A => X) => (B => X) => X
def fold[X](fa: A=>X, fb: B=>X) = this match {
case Left(a) => fa(a)
case Right(b) => fb(b)
}
65. Step by step: handling ending cases
invocationOrError.fold(println, identity)
fold[X] ~
Either[A, B] => (A => X) => (B => X) => X
In this case, if there is an error (a Left value) it
prints it to the console. If all went OK (a Right
value) it does nothing, because the method
was already executed as a side-effect
66. instantiate?
def instantiate(paramList: List[ru.Symbol], argList: List[String]): Either[Error, List[(Name, Any)]] = {
val params = paramList.map(p => p.name.encodedName.toString -> p.typeSignature)
val paramNames = params.unzip._1
val argsOptName = assignNames(argList)
val argsPartition = argsOptName.partition(_._1.isEmpty)
val unnamedArgs = argsPartition._1.unzip._2
val namedArgsTmp = argsPartition._2.collect { case (Some(n), value) => n -> value }
def sortFunc(s: String): Int = { val i = paramNames.indexOf(s); if (i == -1) Int.MaxValue else i }
val namedArgs = namedArgsTmp.sortBy(p => sortFunc(p._1))
val argsNames = namedArgs.unzip._1
val (unreferencedParams, referencedParams) = params.partition(p => !argsNames.contains(p._1))
val unreferenced = instantiateUnreferencedParams(unreferencedParams, unnamedArgs)
val referenced = instantiateParams(referencedParams, namedArgs)
for {
unref <- unreferenced.right
ref <- referenced.right
} yield {
(unref ++ ref).sortBy(p => sortFunc(p._1))
}
}
68. Example:
Suppose we want to query user information,
but it is scattered in multiple servers (ldap and
database).
Most of the time we will be searching by name,
but sometimes we will want to search by uid or
by the user login.
And we want it now! :)
69. Example: usr
So we create a command `usr` with the
following arguments:
name: Option[String]
limit: Option[Int]
uid: Option[String]
login: Option[String]
debug: Option[Boolean]
70. Example: usr
So we create a command `usr` with the
following arguments:
name: Option[String]
limit: Option[Int]
uid: Option[String]
login: Option[String]
debug: Option[Boolean]
limit the number of
results
71. Example: usr
So we create a command `usr` with the
following arguments:
name: Option[String]
limit: Option[Int]
uid: Option[String]
login: Option[String]
debug: Option[Boolean]
extra debug info?
72. Example: usr
So we create a command `usr` with the
following arguments:
name: Option[String]
limit: Option[Int]
uid: Option[String]
login: Option[String]
debug: Option[Boolean]
First so they can be
used without name
73. Example: usr
So we create a command `usr` with the
following arguments:
name: Option[String]
limit: Option[Int]
uid: Option[String]
login: Option[String]
debug: Option[Boolean]
Any individual
argument is optional
74. Example: usr
So we create a command `usr` with the
following arguments:
name: Option[String]
limit: Option[Int]
uid: Option[String]
login: Option[String]
debug: Option[Boolean]
String, Int, Boolean ...
86. futRes.onComplete(printResult)
def onComplete[U](f: Try[T] => U): Unit
When this Future finishes, either correctly (Success) or
with an exception (Failure), apply the function f which
knows how to handle both cases to compute some side
effect
Example: completing futures
Either[Throwable, T]
Try[T] =
Success(t: T)
| Failure(e: Throwable)
~
~
87. futRes.onComplete(printResult)
def onComplete[U](f: Try[T] => U): Unit
In this case the side effect is just printing the result to the
console.
Example: completing futures
Either[Throwable, T]~
~
Try[T] =
Success(t: T)
| Failure(e: Throwable)
91. Future.sequence(
Seq(futUsrLDAPA, futUsrLDAPB, futUsrDB))
def sequence[A, M[_]](
in: M[Future[A]]): Future[M[A]]
Convert some container M of Future[A] in a Future M[A].
Useful to reduce many Futures into a single Future.
Example: sequencing futures
92. Future.sequence(
Seq(futUsrLDAPA, futUsrLDAPB, futUsrDB))
def sequence[A, M[_]](
in: M[Future[A]]): Future[M[A]]
Convert some container M of Future[A] in a Future M[A].
Useful to reduce many Futures into a single Future.
In this case we reduce three independent future results to a
single future result with a Seq of the individual results.
Example: sequencing futures
93. implicit class TryHarder[T](val t: Try[T])
extends AnyVal {
def toEither: Either[Throwable, T] = t match {
case Success(s) => Right(s)
case Failure(f) => Left(f)
}
def fold[U](success: T => U,
failure: Throwable => U): U =
toEither.fold(failure, success)
}
Example: folding on Try
94. implicit class TryHarder[T](val t: Try[T])
extends AnyVal {
def toEither: Either[Throwable, T] = t match {
case Success(s) => Right(s)
case Failure(f) => Left(f)
}
def fold[U](success: T => U,
failure: Throwable => U): U =
toEither.fold(failure, success)
}
Example: folding on Try
Try is pretty much a
specialized Either
95. implicit class TryHarder[T](val t: Try[T])
extends AnyVal {
def toEither: Either[Throwable, T] = t match {
case Success(s) => Right(s)
case Failure(f) => Left(f)
}
def fold[U](success: T => U,
failure: Throwable => U): U =
toEither.fold(failure, success)
}
Example: folding on Try
Try is pretty much a
specialized Either
96. Example: fixing the bug
object usr extends optional.Application {
def main(name: Option[String], limit: Option[Int], uid: Option[String],
login: Option[String], debug: Option[Boolean]) {
if (Seq(name, uid, login).flatten.isEmpty) {
println("You must specify at least one search criteria")
System.exit(1)
}
val effDebug = debug.getOrElse(false)
val futUsrLDAPA = Future { ldapA.findUsr(name, limit, uid, login) }
val futUsrLDAPB = Future { ldapB.findUsr(name, limit, uid, login) }
val futUsrDB = Future { dbase.findUsr(name, limit, uid, login) }
futUsrLDAPA.onComplete(printResult("--- LDAP A ---", debug = effDebug))
futUsrLDAPB.onComplete(printResult("--- LDAP B ---", debug = effDebug))
futUsrDB.onComplete(printResult("--- Data Base ---", debug = effDebug))
val res = Await.ready(
Future.sequence(Seq(futUsrLDAPA, futUsrLDAPB, futUsrDB)), Duration.Inf)
}
}
The problem is that onComplete
executes after the Future is
completed.
Await only awaits to the completion,
not the execution of onComplete and
the program can terminate “too soon”.
97. implicit class FutureOps[T](val f: Future[T])
extends AnyVal {
def continue[S](
cont: Try[T] => S): Future[S] = {
val p = Promise[S]()
f.onComplete { tt =>
p.complete(Try(cont(tt)))
}
p.future
}
}
Example: fixing the bug
98. implicit class FutureOps[T](val f: Future[T])
extends AnyVal {
def continue[S](
cont: Try[T] => S): Future[S] = {
val p = Promise[S]()
f.onComplete { tt =>
p.complete(Try(cont(tt)))
}
p.future
}
}
Example: fixing the bug
Like onComplete but
returning another Future
99. Example: now works :)
object usr extends optional.Application {
def main(name: Option[String], limit: Option[Int], uid: Option[String],
login: Option[String], debug: Option[Boolean]) {
if (Seq(name, uid, login).flatten.isEmpty) {
println("You must specify at least one search criteria")
System.exit(1)
}
val effDebug = debug.getOrElse(false)
val futUsrLDAPA = Future { ldapA.findUsr(name, limit, uid, login) }
val futUsrLDAPB = Future { ldapB.findUsr(name, limit, uid, login) }
val futUsrDB = Future { dbase.findUsr(name, limit, uid, login) }
val endLDAPA = futUsrLDAPA.continue(printResult("--- LDAP A ---"))
val endLDAPB = futUsrLDAPB.continue(printResult("--- LDAP B ---"))
val endDB = futUsrDB.continue(printResult("--- Data Base ---"))
val res = Await.ready(
Future.sequence(Seq(endLDAPA, endLDAPB, endDB)), Duration.Inf)
}
}