Created
January 11, 2016 23:20
-
-
Save danking/0400007107f862991182 to your computer and use it in GitHub Desktop.
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
data Criteria = Criteria (Conjunction (Disjunction Term)) (Disjunction (Conjunction Term)) | |
deriving Show | |
data Term = Term String | |
deriving Show | |
data Conjunction a = Conjunction [a] | |
deriving Show | |
data Disjunction a = Disjunction [a] | |
deriving Show | |
class ToSql a where | |
toSql :: a -> String | |
toComposableSql :: ToSql a => a -> String | |
toComposableSql x = "(" ++ (toSql x) ++ ")" | |
instance ToSql Criteria where | |
toSql (Criteria inclusion exclusion) = | |
(toComposableSql inclusion) ++ " MINUS " ++ (toComposableSql exclusion) | |
instance ToSql a => ToSql (Conjunction a) where | |
toSql (Conjunction conjuncts) = | |
foldl (\x y -> x ++ " INTERSECT " ++ y) | |
"(select * from observation_fact)" | |
(map toComposableSql conjuncts) | |
instance ToSql a => ToSql (Disjunction a) where | |
toSql (Disjunction disjuncts) = | |
foldl (\x y -> x ++ " UNION " ++ y) | |
"(select * from observation_fact where 1=0)" | |
(map toComposableSql disjuncts) | |
instance ToSql Term where | |
toSql (Term id) = | |
"select * form observation_fact where concept_cd = '"++id++"'" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What the Heck is class?
The block:
is equivalent to the Java code:
What the Heck is instance?
The
instance
definitions that follow are all basically implementations of this interface. For example:Is something like:
Assuming we have an appropriate definition of
toComposableSql
somewhere else in that class.What are fat arrows?
Fat arrows play the same role as type constraints in Java like:
So we can read this:
as:
Conclusion
I think this code is very declarative. It's easy to read and believe that it's correct. There's also never any
NullPointerExceptions
.We can write Java code like this too, as my examples show. However, Java can often feel a lot more verbose than Haskell. Moreover, in Haskell you can monkey patch existing classes (like
String
) with new interfaces, but we cannot do this in Java.Some Notes on The Type Parameter in ToSql
In Haskell, the
ToSql a
type takes a type parameter, thea
. In Java, we don't need the type parameter because our function has the impliedthis
argument. If we wanted to write a binary function in Haskell like:then the equivalent Java code is:
Which is different from
add(AddAble a)
because the former requires that the argument is the same class, not just implements the same interface.