Obtain better data accuracy using reference tablesKiran Venna
Data accuracy can be improved tremendously by using reference tables, especially when data is loaded from external files into target tables. Checking the data accuracy of source tables can be easily done with help of reference tables. By using SAS® macro,
data accuracy for many files can be performed with a single reference table. Step by step approach to build reference tables and a way to automate the data accuracy
checks will be discussed in this paper.
Given what a beautiful and mature functional programming language R is, there is a surprising, though understandable, lack of visibility of functional programming techniques in R. This is a talk given to the Mumbai R meetup group in October/November, 2014, meant to introduce the audience to Functional Programming in R.
Best corporate-r-programming-training-in-mumbaiUnmesh Baile
Vibrant Technologies is headquarted in Mumbai,India.We are the best Teradata training provider in Navi Mumbai who provides Live Projects to students.We provide Corporate Training also.We are Best Teradata Database classes in Mumbai according to our students and corporates
Obtain better data accuracy using reference tablesKiran Venna
Data accuracy can be improved tremendously by using reference tables, especially when data is loaded from external files into target tables. Checking the data accuracy of source tables can be easily done with help of reference tables. By using SAS® macro,
data accuracy for many files can be performed with a single reference table. Step by step approach to build reference tables and a way to automate the data accuracy
checks will be discussed in this paper.
Given what a beautiful and mature functional programming language R is, there is a surprising, though understandable, lack of visibility of functional programming techniques in R. This is a talk given to the Mumbai R meetup group in October/November, 2014, meant to introduce the audience to Functional Programming in R.
Best corporate-r-programming-training-in-mumbaiUnmesh Baile
Vibrant Technologies is headquarted in Mumbai,India.We are the best Teradata training provider in Navi Mumbai who provides Live Projects to students.We provide Corporate Training also.We are Best Teradata Database classes in Mumbai according to our students and corporates
Single-Row Functions in orcale Data baseSalman Memon
After completing this lesson, you should be able to
do the following:
Describe various types of functions availablein SQL
Use character, number, and date functions in SELECT statements
Describe the use of conversion functions
http://phpexecutor.com
core & advanced java classes in Mumbai
best core & advanced java classes in Mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
Aggregating Data Using Group FunctionsSalman Memon
After completing this lesson, you should be able to
do the following:
Identify the available group functions
Describe the use of group functions
Group data using the GROUP BY clause
Include or exclude grouped rows by using the HAVING clause
http://phpexecutor.com
Displaying Data from Multiple Tables - Oracle Data BaseSalman Memon
After completing this lesson, you should be able to
do the following:
Write SELECT statements to access data from more than one table using equality and nonequality joins
View data that generally does not meet a join condition by using outer joins
Join a table to itself by using a self join
http://phpexecutor.com
An Introduction to Functional Programming - DeveloperUG - 20140311Andreas Pauley
Functional Programming has received increased attention in recent years.
Some people claim that it provides important benefits to programming, but it seems somewhat inaccessible. You have to navigate through lots of academic-speak and look at examples that might only make sense to a professor in mathematics.
In this presentation I try to present some of the essential ideas behind functional programming, with simple examples first in Python and then in Haskell.
What do you need to know in order to enjoy this talk?
I have made some of the following assumptions about the kind of developer who will benefit from this talk:
1. You are a programmer using any programming language
2. You can read Python examples (it's WAY shorter on slides than C# or Java)
3. You are interested enough in improving your code that you are willing to challenge some common assumptions.
Here is a mock assessment test for the 1Z0-146 certification exam which can be your final warm up game before you appear for the real exam. Questions follow similar pattern but also test your basic understanding on a concept. For answer key – comment on the post with your email id and I shall send across to you the same.
I hope the readers of my book will find the mock paper quite handy while the rest of you will discover the areas to dive in further.
Are you an Oracle developer or a DBA?
Do you know the difference between aggregate and analytic functions?
Without complex sub-queries or self-joins, do you know how to:
Calculate running/cumulative totals and moving/centered averages?
List products with revenues above or below their peers or product groups?
Compute the ratio of one category’s sales to the total sales?
Select the Top-N or Top N % of the customers/products?
Classify advertisers into quartiles/n-tiles based on the revenue potential?
Compare period-over-period (year-over-year, month-over-month) growth and rank advancement?
Convert rows into columns (pivot), columns into rows (unpivot) or aggregate strings?
Perform what-if analysis and hypothetical ranking?
Analytic functions are more performant because tables need to be scanned only once. They make you more productive because there is no need to write procedural code. No wonder Tom Kyte, a well-respected Oracle guru, says analytic functions are the best thing to happen after the sliced bread.
In the first half, I will cover the basics of the various analytic functions:
Ranking: RANK, DENSE_RANK, ROW_NUMBER, NTILE, CUME_DIST, PERCENTILE_RANK
Windowing: SUM, AVG, MAX, MIN, FIRST_VALUE, LAST_VALUE
Reporting: RATIO_TO_REPORT
Others: FIRST/LAST, LEAD/LAG, hypothetical ranking,
In the second half, I will show how powerful these functions are with a few examples.
If there is time, I will cover enhanced aggregation (ROLLUP, CUBE, GROUPING SET extensions to GROUP BY clause)
This class would be useful for both developers and DBAs alike, especially for those working in Analytic, Business Intelligence, and Datawarehouse environments.
Are you already an expert in analytic functions? Then come and help me refine the content.
For more info, read
http://download.oracle.com/docs/cd/E11882_01/server.112/e16579/analysis.htm
http://download.oracle.com/docs/cd/E11882_01/server.112/e16579/aggreg.htm
rollup, cross-tabulation across different dimensions using ROLLUP, CUBE and GROUPING SETS extension to GROUP BY clause
, most active time-periods (i.e. days when the most number of tickets are open in BZ, hours with the most take-off and landings, months with the highest sales, 5-minute periods with the maximum number of calls made, etc)
data densification?
their rank last year, this year, rank growth, running/cumulative total (Year-To-Date/Month-To-Date summation), moving averages, Year-Over-Year comparison, sales projection, average/min/max time between one sale and the next sale, products with above and below average sales.
overall average, sum, departmental average, sum, ranking, job wise ranking in one SQL.
The presentation is a brief case study of R Programming Language. In this, we discussed the scope of R, Uses of R, Advantages and Disadvantages of the R programming Language.
Single-Row Functions in orcale Data baseSalman Memon
After completing this lesson, you should be able to
do the following:
Describe various types of functions availablein SQL
Use character, number, and date functions in SELECT statements
Describe the use of conversion functions
http://phpexecutor.com
core & advanced java classes in Mumbai
best core & advanced java classes in Mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
Aggregating Data Using Group FunctionsSalman Memon
After completing this lesson, you should be able to
do the following:
Identify the available group functions
Describe the use of group functions
Group data using the GROUP BY clause
Include or exclude grouped rows by using the HAVING clause
http://phpexecutor.com
Displaying Data from Multiple Tables - Oracle Data BaseSalman Memon
After completing this lesson, you should be able to
do the following:
Write SELECT statements to access data from more than one table using equality and nonequality joins
View data that generally does not meet a join condition by using outer joins
Join a table to itself by using a self join
http://phpexecutor.com
An Introduction to Functional Programming - DeveloperUG - 20140311Andreas Pauley
Functional Programming has received increased attention in recent years.
Some people claim that it provides important benefits to programming, but it seems somewhat inaccessible. You have to navigate through lots of academic-speak and look at examples that might only make sense to a professor in mathematics.
In this presentation I try to present some of the essential ideas behind functional programming, with simple examples first in Python and then in Haskell.
What do you need to know in order to enjoy this talk?
I have made some of the following assumptions about the kind of developer who will benefit from this talk:
1. You are a programmer using any programming language
2. You can read Python examples (it's WAY shorter on slides than C# or Java)
3. You are interested enough in improving your code that you are willing to challenge some common assumptions.
Here is a mock assessment test for the 1Z0-146 certification exam which can be your final warm up game before you appear for the real exam. Questions follow similar pattern but also test your basic understanding on a concept. For answer key – comment on the post with your email id and I shall send across to you the same.
I hope the readers of my book will find the mock paper quite handy while the rest of you will discover the areas to dive in further.
Are you an Oracle developer or a DBA?
Do you know the difference between aggregate and analytic functions?
Without complex sub-queries or self-joins, do you know how to:
Calculate running/cumulative totals and moving/centered averages?
List products with revenues above or below their peers or product groups?
Compute the ratio of one category’s sales to the total sales?
Select the Top-N or Top N % of the customers/products?
Classify advertisers into quartiles/n-tiles based on the revenue potential?
Compare period-over-period (year-over-year, month-over-month) growth and rank advancement?
Convert rows into columns (pivot), columns into rows (unpivot) or aggregate strings?
Perform what-if analysis and hypothetical ranking?
Analytic functions are more performant because tables need to be scanned only once. They make you more productive because there is no need to write procedural code. No wonder Tom Kyte, a well-respected Oracle guru, says analytic functions are the best thing to happen after the sliced bread.
In the first half, I will cover the basics of the various analytic functions:
Ranking: RANK, DENSE_RANK, ROW_NUMBER, NTILE, CUME_DIST, PERCENTILE_RANK
Windowing: SUM, AVG, MAX, MIN, FIRST_VALUE, LAST_VALUE
Reporting: RATIO_TO_REPORT
Others: FIRST/LAST, LEAD/LAG, hypothetical ranking,
In the second half, I will show how powerful these functions are with a few examples.
If there is time, I will cover enhanced aggregation (ROLLUP, CUBE, GROUPING SET extensions to GROUP BY clause)
This class would be useful for both developers and DBAs alike, especially for those working in Analytic, Business Intelligence, and Datawarehouse environments.
Are you already an expert in analytic functions? Then come and help me refine the content.
For more info, read
http://download.oracle.com/docs/cd/E11882_01/server.112/e16579/analysis.htm
http://download.oracle.com/docs/cd/E11882_01/server.112/e16579/aggreg.htm
rollup, cross-tabulation across different dimensions using ROLLUP, CUBE and GROUPING SETS extension to GROUP BY clause
, most active time-periods (i.e. days when the most number of tickets are open in BZ, hours with the most take-off and landings, months with the highest sales, 5-minute periods with the maximum number of calls made, etc)
data densification?
their rank last year, this year, rank growth, running/cumulative total (Year-To-Date/Month-To-Date summation), moving averages, Year-Over-Year comparison, sales projection, average/min/max time between one sale and the next sale, products with above and below average sales.
overall average, sum, departmental average, sum, ranking, job wise ranking in one SQL.
The presentation is a brief case study of R Programming Language. In this, we discussed the scope of R, Uses of R, Advantages and Disadvantages of the R programming Language.
Functional programming in Scala. Looking at various examples of defining a program first and executing it at some later stage, separating pure functions from side effects.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
This is an introductory SCALA workshop for a JAVA developer. Hence, we're going to explore 'functional' side of the language. SCALA is 50% OOP (Object-Oriented-Programming) and 50% FP (Functional-Programming). Main principles of FP are discussed, such as: tail-recursion, currying, pure-functions, lazy evaluation etc.) along with some examples in code.
We look at the basic keywords and constructs in SCALA.
In the end SCALA tools which are helpful for developers are listed.
Scala is an alternative JVM language with both object-oriented and functional programming paradigms. Scala development with the Java EE 7 platform is definitely possible and can be a pleasant experience. If you have uncertainty about how Scala can fit around the Java EE 7 platform, then this session aims to illustrate the huge benefit that Scala adoption can bring to the platform. Many other developers are taking advantage and the challenge of the JVM’s capability of being a vessel for multi-language programming. You no longer have to write every single project using Java, even if you like Lambdas experiences. For the developer and engineering terms that feeling a little braver than usual, Scala is attractive as it is strongly typed and lets you set the gauge on how object oriented or how functional you want to be. You will learn how to reuse the annotations and creating Scala plain object safely and concisely. This session will highlight and contrast the experience I had developing Scala solutions with Java EE, and there will be plenty of advice about using the functional programming features against the Java object oriented API.
Scala language overview
Java EE 7 architecture and design
WildFly 8 application server
Using Gradle as a build tool
How to create beans in Scala with dependency injection
JAX-RS endpoints
Servlet Endpoints
JMS Messaging
Scala adoption advice and hints for sustainable team development
JavaCro 2014 Scala and Java EE 7 Development ExperiencesPeter Pilgrim
Scala is an alternative JVM language with both object-oriented and functional programming paradigms. Scala development with the Java EE 7 platform is definitely possible and can be a pleasant experience. If you have uncertainty about how Scala can fit around the Java EE 7 platform, then this session aims to illustrate the huge benefit that Scala adoption can bring to the platform. Many other developers are taking advantage and the challenge of the JVM’s capability of being a vessel for multi-language programming. You no longer have to write every single project using Java, even if you like Lambdas experiences.
For the developer and engineering terms that feeling a little braver than usual, Scala is attractive as it is strongly typed and lets you set the gauge on how object oriented or how functional you want to be. You will learn how to reuse the annotations and creating Scala plain object safely and concisely.
This session will highlight and contrast the experience I had developing Scala solutions with Java EE, and there will be plenty of advice about using the functional programming features against the Java object oriented API.
Scala language overview
Java EE 7 architecture and design
Using Gradle as a build tool
How to create beans in Scala with dependency injection
JAX-RS endpoints
Servlet Endpoints
JMS Messaging
Scala adoption advice and hints for sustainable team development
The great attractiveness of purely functional languages is their ability to depart from sequential order of computation. Theoretically, it enables two important features of the compiler:
1) The ability to reorder computation flow, making the program implicitly parallelisable. Modern imperative language compilers, even using careful synchronization of concurrent code, still generate huge chunks of sequential instructions that need to be executed on a single processor core; a purely functional language compilers can dispatch very small chunks to many (hundreds and thousands) of cores, carefully eliminating as many execution path dependencies as possible.
2) As the compiler formalizes different types of side effects, it can detect a whole new class of program errors at compile time, including resource acquisition and releasing problems, concurrent access to shared resources, many types of deadlocks etc. It is not yet a full-fledged program verification, but it is a big step in that direction.
Scala is a semi-imperative language with strong support for functional programming and rich type system. One can isolate the purely functional core of the language which can be put on the firm mathematical foundation of dependent type theories. We argue that it is possible to treat Scala code as it's written by now as an implicit do-notation which can be then reduced to a purely functional core by means of recently introduced Scala macros. The formalism of arrows and applicative contexts can bring Scala to a full glory of an implicitly parallelisable programming language, while still keeping its syntax mostly unchanged.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Water billing management system project report.pdfKamal Acharya
Our project entitled “Water Billing Management System” aims is to generate Water bill with all the charges and penalty. Manual system that is employed is extremely laborious and quite inadequate. It only makes the process more difficult and hard.
The aim of our project is to develop a system that is meant to partially computerize the work performed in the Water Board like generating monthly Water bill, record of consuming unit of water, store record of the customer and previous unpaid record.
We used HTML/PHP as front end and MYSQL as back end for developing our project. HTML is primarily a visual design environment. We can create a android application by designing the form and that make up the user interface. Adding android application code to the form and the objects such as buttons and text boxes on them and adding any required support code in additional modular.
MySQL is free open source database that facilitates the effective management of the databases by connecting them to the software. It is a stable ,reliable and the powerful solution with the advanced features and advantages which are as follows: Data Security.MySQL is free open source database that facilitates the effective management of the databases by connecting them to the software.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
We have compiled the most important slides from each speaker's presentation. This year’s compilation, available for free, captures the key insights and contributions shared during the DfMAy 2024 conference.
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesChristina Lin
Traditionally, dealing with real-time data pipelines has involved significant overhead, even for straightforward tasks like data transformation or masking. However, in this talk, we’ll venture into the dynamic realm of WebAssembly (WASM) and discover how it can revolutionize the creation of stateless streaming pipelines within a Kafka (Redpanda) broker. These pipelines are adept at managing low-latency, high-data-volume scenarios.
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Scala Validation with Functional Programming
1. Validation with Functional Programming
Sukant Hajra / @shajra
April 14, 2016
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 1 / 61
2. Some Goals
explore data structures for managing errors
use type classes to get nice APIs (DSLs)
see some examples with parsing
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 2 / 61
9. scalaz.ValidationNel
Dangerous flatMap
scala> "fail 1".failureNel[Int].flatMap { a =>
| "fail 2".failureNel[Int].map { b =>
| a + b
| }
| }
warning: there was one deprecation warning; re-run with
-deprecation for details
res16: scalaz.Validation[scalaz.NonEmptyList[String],Int] =
Failure(NonEmptyList(fail 1))
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 9 / 61
10. Composition
Defining some functions
import scalaz.std.function._
import scalaz.syntax.compose._
def add: Int => Int => Int = a => b => a + b
val mult: Int => Int => Int = a => b => a * b
Usage
scala> add(2) >>> mult(10) >>> add(3) apply 0
res18: Int = 23
scala> add(2) <<< mult(10) <<< add(3) apply 0
res19: Int = 32
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 10 / 61
11. What more is possible?
Consider this broken config
val confText = """
name = "Donald Trump"
year_born = 1946
nemesis {
year_born = "Age of Enlightment"
name = 1650
}
"""
Both nemesis.year_born and nemesis.name have the wrong type.
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 11 / 61
12. What more is possible?
Could we catch both defects with this API?
case class UserData(name: String, yearBorn: Int)
def sub(key: String): ConfRead[Json] = ???
def required[A : Readable](key: String): ConfRead[A] = ???
val userRead: ConfRead[UserData] =
(required[String]("name") |@| required[Int]("year_born")).
apply(UserData)
def fullRead: ConfRead[(UserData, UserData)] =
(userRead |@| (sub("nemesis") >>> userRead)).tupled
Config.parse map fullRead.read
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 12 / 61
13. Type Classes (a review)
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 13 / 61
14. Useful type classes
We’ll quickly review:
Semigroup
Compose
Covariant Functor
Applicative Functor
Monad
Also useful, but not discussed today:
Profunctor
Arrow or Strong Profunctor
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 14 / 61
15. High quality type classes
Type classes are statically dispatched interfaces that should
be implementable for many data types
provide functions that lead to rich libraries
have only one instance per type (global uniqueness) 1
have laws (strong contracts).
Auto-deriving instances is also nice.
1
Global uniqueness is debated by a few
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 15 / 61
16. Semigroup
Definition
trait Semigroup[A] {
def append(x: A, y: A): A
}
object Semigroup {
def apply[A](implicit ev: Semigroup[A]): Semigroup[A] = ev
}
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 16 / 61
17. Semigroup
Laws
trait SemigroupLaws[A] extends Semigroup[A] {
def semigroupAssociativity(x: A, y: A, z: A) =
append(x, append(y, z)) == append(append(x, y), z)
}
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 17 / 61
18. Semigroup
Syntax
implicit class SemigroupOps[A : Semigroup](a1: A) {
def |+|(a2: A): A = Semigroup[A].append(a1, a2)
}
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 18 / 61
37. Disjunction
Definition
object disj {
sealed trait Disj[A, B] {
def fold[C](ifLeft: A => C)(ifRight: B => C) =
this match {
case LeftD(a) => ifLeft(a)
case RightD(b) => ifRight(b)
}
}
case class LeftD[A, B](a: A) extends Disj[A, B]
case class RightD[A, B](b: B) extends Disj[A, B]
}; import disj._
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 37 / 61
38. Disjunction
Syntax
implicit class DisjOps[A](a: A) {
def left[B]: Disj[A, B] = LeftD(a)
def right[B]: Disj[B, A] = RightD(a)
}
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 38 / 61
41. Validation
Definition
object checked {
sealed trait Checked[A, B] {
def fold[C](ifFail: A => C)(ifPass: B => C) =
this match {
case Fail(a) => ifFail(a)
case Pass(b) => ifPass(b)
}
}
case class Fail[A, B](a: A) extends Checked[A, B]
case class Pass[A, B](b: B) extends Checked[A, B]
}; import checked._
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 41 / 61
42. Validation
Syntax
implicit class CheckedOps1[A](a: A) {
def pass[B]: Checked[B, A] = Pass(a)
def fail[B]: Checked[A, B] = Fail(a)
def passNel[B]: Checked[Nel[B], A] = Pass(a)
def failNel[B]: Checked[Nel[A], B] = Fail(Nel of a)
}
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 42 / 61
47. Read
Applicative Instance
implicit def readApplicative[F[_] : Applicative, A]
: Applicative[Read[F, A, ?]] =
new Applicative[Read[F, A, ?]] {
def point[B](b: => B) = Read { a => b.pure[F] }
def ap[B, C](r: => Read[F, A, B])(f: => Read[F, A, B=>C]) =
Read { a => (f.read(a) |@| r.read(a)) { _ apply _ } }
}
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 47 / 61
48. ReadC
Definition
case class ReadC[A, E, B](read: A => Checked[E, B])
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 48 / 61
49. ReadC
Instances
implicit def readCCompose[E]: Compose[ReadC[?, E, ?]] =
new Compose[ReadC[?, E, ?]] {
def compose[A, B, C]
(f: ReadC[B, E, C], g: ReadC[A, E, B]) =
ReadC { a => g.read(a).fold(_.fail[C])(f.read) }
}
implicit def readCApplicative[A, E : Semigroup]
: Applicative[ReadC[A, E, ?]] =
new Applicative[ReadC[A, E, ?]] {
def point[B](b: => B) =
ReadC { a => b.pure[Checked[E, ?]] }
def ap[B, C]
(r: => ReadC[A, E, B])(f: => ReadC[A, E, B=>C]) =
ReadC { a => (f.read(a) |@| r.read(a)) { _ apply _ } }
}
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 49 / 61
60. Wrapping up
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 60 / 61
61. This material
is compiler-checked (half-literate programming) using:
Rob Norris’s tut SBT plugin
pandoc
LATEX
Beamer
is at https://github.com/shajra/shajra-presentations.
Sukant Hajra / @shajra Validation with Functional Programming April 14, 2016 61 / 61