Explanation of class instance declarations - class

I am following a tutorial and found this code:
data A = B | C deriving(Eq)
class K a where
f :: a -> Bool
instance K A where
f x = x == C
f _ = False
call = f B
Why do I need f _ = False? I get the same result without it.

The answer is simply: you don't need f _ = False here. In fact, if you compile with -Wall then the compiler will warn you that this clause is redundant, because the f x = ... clause already catches everything.
If the tutorial told you to have that extra clause, well, it's wrong.

As pointed out, it's not necessary.
You might need (or want) that line, though, if you had a slightly different definition, one that does not require an Eq instance:
data A = B | C
class K a where
f :: a -> Bool
instance K A where
f C = True
f _ = False
Instead of comparing x to C, you can match the argument directly against C, then define f to return False for all other values. This makes more sense if there were more constructors that could produce False.
data A' = B | C | D
instance K A' where
f C = True
f _ = False -- in place of f B = False and f D = False

Related

A, B and C are three boolean values. Write an expression in terms of only !(not) and &&(and) which always gives the same value as A||B||C

Chanced upon this beautiful problem. Since I am new to Boolean expressions, it is looking quite difficult.
I guess parentheses can be used.
If one of A, B, C is true, A||B||C must be true. Using AND and NOT, it can be done but, how do we know which one has which value?
I tried using truth tables, but three variables were too much.
Any ideas on how to solve, or at least how to make it faster?
Learn De Morgan's laws. It's a little piece of a basic knowledge for a programmer.
They state, among others, that not(X or Y) = (not X) and (not Y).
If you negate both sides and then apply the formula twice—first to ((A or B) or C), treating the (A or B) subexpression as X, and then to (A or B) itself—you'll get the desired result:
A || B || C =
(A || B) || C =
!(!(A || B) && !C) =
!((!A || !B) && !C) =
!(!A && !B && !C)
DeMorgan's Law (one of them, anyway), normally applied to two variables, states that:
A or B == not (not A and not B)
But this works equally well for three (or more) variables:
A or B or C == not (not A and not B and not C)
This becomes obvious when you realise that A or B or C is true if any of them are true, the only way to get false if if all of them are false.
And, only if they're all false will not A and not B and not C give true (hence not(that) will give false). For confirmation, here's the table, where you'll see that the A or B or C and not(notA and notB and notC) columns give the same values:
A B C A or B or C notA notB notC not(notA and notB and notC)
----- ----------- -------------- ---------------------------
f f f f t t t f
f f t t t t f t
f t f t t f t t
f t t t t f f t
t f f t f t t t
t f t t f t f t
t t f t f f t t
t t t t f f f t

Similar record types in a list/array in purescript

Is there any way to do something like
first = {x:0}
second = {x:1,y:1}
both = [first, second]
such that both is inferred as {x::Int | r} or something like that?
I've tried a few things:
[{x:3}] :: Array(forall r. {x::Int|r}) -- nope
test = Nil :: List(forall r. {x::Int|r})
{x:1} : test -- nope
type X r = {x::Int | r}
test = Nil :: List(X) -- nope
test = Nil :: List(X())
{x:1} : test
{x:1, y:1} : test -- nope
Everything I can think of seems to tell me that combining records like this into a collection is not supported. Kind of like, a function can be polymorphic but a list cannot. Is that the correct interpretation? It reminds me a bit of the F# "value restriction" problem, though I thought that was just because of CLR restrictions whereas JS should not have that issue. But maybe it's unrelated.
Is there any way to declare the list/array to support this?
What you're looking for is "existential types", and PureScript just doesn't support those at the syntax level the way Haskell does. But you can roll your own :-)
One way to go is "data abstraction" - i.e. encode the data in terms of operations you'll want to perform on it. For example, let's say you'll want to get the value of x out of them at some point. In that case, make an array of these:
type RecordRep = Unit -> Int
toRecordRep :: forall r. { x :: Int | r } -> RecordRep
toRecordRep {x} _ = x
-- Construct the array using `toRecordRep`
test :: Array RecordRep
test = [ toRecordRep {x:1}, toRecordRep {x:1, y:1} ]
-- Later use the operation
allTheXs :: Array Int
allTheXs = test <#> \r -> r unit
If you have multiple such operations, you can always make a record of them:
type RecordRep =
{ getX :: Unit -> Int
, show :: Unit -> String
, toJavaScript :: Unit -> Foreign.Object
}
toRecordRep r =
{ getX: const r.x
, show: const $ show r.x
, toJavaScript: const $ unsafeCoerce r
}
(note the Unit arguments in every function - they're there for the laziness, assuming each operation could be expensive)
But if you really need the type machinery, you can do what I call "poor man's existential type". If you look closely, existential types are nothing more than "deferred" type checks - deferred to the point where you'll need to see the type. And what's a mechanism to defer something in an ML language? That's right - a function! :-)
newtype RecordRep = RecordRep (forall a. (forall r. {x::Int|r} -> a) -> a)
toRecordRep :: forall r. {x::Int|r} -> RecordRep
toRecordRep r = RecordRep \f -> f r
test :: Array RecordRep
test = [toRecordRep {x:1}, toRecordRep {x:1, y:1}]
allTheXs = test <#> \(RecordRep r) -> r _.x
The way this works is that RecordRep wraps a function, which takes another function, which is polymorphic in r - that is, if you're looking at a RecordRep, you must be prepared to give it a function that can work with any r. toRecordRep wraps the record in such a way that its precise type is not visible on the outside, but it will be used to instantiate the generic function, which you will eventually provide. In my example such function is _.x.
Note, however, that herein lies the problem: the row r is literally not known when you get to work with an element of the array, so you can't do anything with it. Like, at all. All you can do is get the x field, because its existence is hardcoded in the signatures, but besides the x - you just don't know. And that's by design: if you want to put anything into the array, you must be prepared to get anything out of it.
Now, if you do want to do something with the values after all, you'll have to explain that by constraining r, for example:
newtype RecordRep = RecordRep (forall a. (forall r. Show {x::Int|r} => {x::Int|r} -> a) -> a)
toRecordRep :: forall r. Show {x::Int|r} => {x::Int|r} -> RecordRep
toRecordRep r = RecordRep \f -> f r
test :: Array RecordRep
test = [toRecordRep {x:1}, toRecordRep {x:1, y:1}]
showAll = test <#> \(RecordRep r) -> r show
Passing the show function like this works, because we have constrained the row r in such a way that Show {x::Int|r} must exist, and therefore, applying show to {x::Int|r} must work. Repeat for your own type classes as needed.
And here's the interesting part: since type classes are implemented as dictionaries of functions, the two options described above are actually equivalent - in both cases you end up passing around a dictionary of functions, only in the first case it's explicit, but in the second case the compiler does it for you.
Incidentally, this is how Haskell language support for this works as well.
Folloing #FyodorSoikin answer based on "existential types" and what we can find in purescript-exists we can provide yet another solution.
Finally we will be able to build an Array of records which will be "isomorphic" to:
exists tail. Array { x :: Int | tail }
Let's start with type constructor which can be used to existentially quantify over a row type (type of kind #Type). We are not able to use Exists from purescript-exists here because PureScript has no kind polymorphism and original Exists is parameterized over Type.
newtype Exists f = Exists (forall a. f (a :: #Type))
We can follow and reimplement (<Ctrl-c><Ctrl-v> ;-)) definitions from Data.Exists and build a set of tools to work with such Exists values:
module Main where
import Prelude
import Unsafe.Coerce (unsafeCoerce)
import Data.Newtype (class Newtype, unwrap)
newtype Exists f = Exists (forall a. f (a :: #Type))
mkExists :: forall f a. f a -> Exists f
mkExists r = Exists (unsafeCoerce r :: forall a. f a)
runExists :: forall b f. (forall a. f a -> b) -> Exists f -> b
runExists g (Exists f) = g f
Using them we get the ability to build an Array of Records with "any" tail but we have to wrap any such a record type in a newtype before:
newtype R t = R { x :: Int | t }
derive instance newtypeRec :: Newtype (R t) _
Now we can build an Array using mkExists:
arr :: Array (Exists R)
arr = [ mkExists (R { x: 8, y : "test"}), mkExists (R { x: 9, z: 10}) ]
and process values using runExists:
x :: Array [ Int ]
x = map (runExists (unwrap >>> _.x)) arr

How are these boolean expressions (truth tables) equivalent?

I am trying to better understand boolean equivalence but this example has me a little stuck.
I am referring to this website: http://chortle.ccsu.edu/java5/Notes/chap40B/ch40B_9.html
It makes sense, but doesn't at the same time... it says that they are equivalent, but the true/false values don't add up/align in a way that makes them out to be equivalent as the table shows they are. Could someone explain this to me?
!(A && B) <-- first expression
(C || D) <-- second expression
The last columns refers to the equivalency of the two expressions, which yes, they are equivalent according to the table. However, I just don't get how the two expressions are equivalent. If A = F, B = F --> T, wouldn't C = F, D = F --> T as well?
A B C D
--------------------
F F T T T
F T T F T
T F F T T
T T F F F
You are confusing yourself when trying to reduce it from the actual expression to single letter variables. On referring the actual link, it would appear that the variables you use can be mapped to the original expressions as follows:
A = speed > 2000
B = memory > 512
C = speed <= 2000
D = memory <= 512
If you look at it, C equals !A and D equals !B. So the expression (C || D) is effectively !((!A) || (!B)). By De Morgan's Law, that is the same as !(A && B).
This table is explaining that !(A && B) is equivalent to !A || !B. The columns C and D appear to be defined as C = !A and D = !B. The last column is C || D
So A = F, B = F certainly implies !(A && B). In this case C = D = T, and so also C || D = T.

How to do pointfree style with long parameter list

I've got a function that creates an Async workflow, and the function that takes 10 arguments in curry style. e.g.
let createSequenceCore a b c d e f g h i j =
async {
...
}
I want to create another function to start that workflow, so I've got
let startSequenceCore a b c d e f g h i j =
Async.StartImmediate (createSequenceCore a b c d e f g h i j)
Is there any way I can get rid of those redundant parameters? I tried the << operator, but that only lets me remove one.
let startSequenceCore a b c d e f g h i =
Async.StartImmediate << (createSequenceCore a b c d e f g h i)
(I added Haskell and Scala to this question even though the code itself is F#, as really what I want is just how to do this kind of currying, which would apply to any; I'd think a Haskell or Scala answer would be easily portable to F# and could well be marked as the correct answer).
NOTE Reasonably well showing that there is not an easy solution to this could also get the bounty.
UPDATE geesh I'm not going to give 100 points to an answer that argues with the question rather than answering it, even if it's the highest voted, so here:
I've got a function that creates an Async workflow, and the function that takes 4 arguments in curry style. e.g.
let createSequenceCore a b c d =
async {
...
}
I want to create another function to start that workflow, so I've got
let startSequenceCore a b c d =
Async.StartImmediate (createSequenceCore a b c d)
Is there any way I can get rid of those redundant parameters? I tried the << operator, but that only lets me remove one.
let startSequenceCore a b c =
Async.StartImmediate << (createSequenceCore a b c)
10 arguments sounds like too many... How about you'd create a record with 10 properties instead, or maybe a DU where you don't need all 10 in every case? Either way, you'd end up with a single argument that way and normal function composition works as expected again.
EDIT: When you actually need it, you can create a more powerful version of the << and >> operators thusly:
let (<.<) f = (<<) (<<) (<<) f
let (<..<) f = (<<) (<<) (<.<) f
let (<...<) f = (<<) (<<) (<..<) f
let flip f a b = f b a
let (>.>) f = flip (<.<) f
let (>..>) f = flip (<..<) f
let (>...>) f = flip (<...<) f
and then you can just write:
let startSequenceCore =
Async.StartImmediate <...< createSequenceCore
or
let startSequenceCore =
createSequenceCore >...> Async.StartImmediate
P.S.: The argument f is there, so that the type inference infers generic args as opposed to obj.
As already mentioned by #Daniel Fabian, 10 arguments is way too many. In my experience even 5 arguments is too many and the code becomes unreadable and error prone. Having such functions usually signals a bad design. See also Are there guidelines on how many parameters a function should accept?
However, if you insist, it's possible to make it point-free, although I doubt it gains any benefit. I'll give an example in Haskell, but I believe it'd be easy to port to F# as well. The trick is to nest the function composition operator:
data Test = Test
deriving (Show)
createSequenceCore :: Int -> Int -> Int -> Int -> Int
-> Int -> Int -> Int -> Int -> Int -> Test
createSequenceCore a b c d e f g h i j = Test
-- the original version
startSequenceCore :: Int -> Int -> Int -> Int -> Int
-> Int -> Int -> Int -> Int -> Int -> IO ()
startSequenceCore a b c d e f g h i j =
print (createSequenceCore a b c d e f g h i j)
-- and point-free:
startSequenceCore' :: Int -> Int -> Int -> Int -> Int
-> Int -> Int -> Int -> Int -> Int -> IO ()
startSequenceCore' =
(((((((((print .) .) .) .) .) .) .) .) .) . createSequenceCore
Replacing f with (f .) lifts a function to work one argument inside, as we can see by adding parentheses to the type of (.):
(.) :: (b -> c) -> ((a -> b) -> (a -> c))
See also this illuminating blog post by Conal Elliott: Semantic editor combinators
You could tuple the arguments to createSequenceCore:
let createSequenceCore(a, b, c, d, e, f, g, h, i, j) =
async {
...
}
let startSequenceCore =
createSequenceCore >> Async.StartImmediate
I am assuming you just want to write clean code as opposed to allow currying one parameter at a time.
Just write your own composeN function.
let compose4 g f x0 x1 x2 x4 =
g (f x0 x1 x2 x4)
let startSequenceCore =
compose4 Async.StartImmediate createSequenceCore

Defining multiple-type container classes in haskell, trouble binding variables

I'm having trouble with classes in haskell.
Basically, I have an algorithm (a weird sort of graph-traversal algorithm) that takes as input, among other things, a container to store the already-seen nodes (I'm keen on avoiding monads, so let's move on. :)). The thing is, the function takes the container as a parameter, and calls just one function: "set_contains", which asks if the container... contains node v. (If you're curious, another function passed in as a parameter does the actual node-adding).
Basically, I want to try a variety of data structures as parameters. Yet, as there is no overloading, I cannot have more than one data structure work with the all-important contains function!
So, I wanted to make a "Set" class (I shouldn't roll my own, I know). I already have a pretty nifty Red-Black tree set up, thanks to Chris Okasaki's book, and now all that's left is simply making the Set class and declaring RBT, among others, as instances of it.
Here is the following code:
(Note: code heavily updated -- e.g., contains now does not call a helper function, but is the class function itself!)
data Color = Red | Black
data (Ord a) => RBT a = Leaf | Tree Color (RBT a) a (RBT a)
instance Show Color where
show Red = "r"
show Black = "b"
class Set t where
contains :: (Ord a) => t-> a-> Bool
-- I know this is nonesense, just showing it can compile.
instance (Ord a) => Eq (RBT a) where
Leaf == Leaf = True
(Tree _ _ x _) == (Tree _ _ y _) = x == y
instance (Ord a) => Set (RBT a) where
contains Leaf b = False
contains t#(Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
Note how I have a pretty stupidly-defined Eq instance of RBT. That is intentional --- I copied it (but cut corners) from the gentle tutorial.
Basically, my question boils down to this: If I comment out the instantiation statement for Set (RBT a), everything compiles. If I add it back in, I get the following error:
RBTree.hs:21:15:
Couldn't match expected type `a' against inferred type `a1'
`a' is a rigid type variable bound by
the type signature for `contains' at RBTree.hs:11:21
`a1' is a rigid type variable bound by
the instance declaration at RBTree.hs:18:14
In the second argument of `(==)', namely `x'
In a pattern guard for
the definition of `contains':
b == x
In the definition of `contains':
contains (t#(Tree c l x r)) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
And I simply cannot, for the life of me, figure out why that isn't working. (As a side note, the "contains" function is defined elsewhere, and basically has the actual set_contains logic for the RBT data type.)
Thanks! - Agor
Third edit: removed the previous edits, consolidated above.
You could also use higher-kinded polyphormism. The way your class is defined it sort of expects a type t which has kind *. What you probably want is that your Set class takes a container type, like your RBT which has kind * -> *.
You can easily modify your class to give your type t a kind * -> * by applying t to a type variable, like this:
class Set t where
contains :: (Ord a) => t a -> a -> Bool
and then modify your instance declaration to remove the type variable a:
instance Set RBT where
contains Leaf b = False
contains t#(Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
So, here is the full modified code with a small example at the end:
data Color = Red | Black
data (Ord a) => RBT a = Leaf | Tree Color (RBT a) a (RBT a)
instance Show Color where
show Red = "r"
show Black = "b"
class Set t where
contains :: (Ord a) => t a -> a -> Bool
-- I know this is nonesense, just showing it can compile.
instance (Ord a) => Eq (RBT a) where
Leaf == Leaf = True
(Tree _ _ x _) == (Tree _ _ y _) = x == y
instance Set RBT where
contains Leaf b = False
contains t#(Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
tree = Tree Black (Tree Red Leaf 3 Leaf) 5 (Tree Red Leaf 8 (Tree Black Leaf 12 Leaf))
main =
putStrLn ("tree contains 3: " ++ test1) >>
putStrLn ("tree contains 12: " ++ test2) >>
putStrLn ("tree contains 7: " ++ test3)
where test1 = f 3
test2 = f 12
test3 = f 7
f = show . contains tree
If you compile this, the output is
tree contains 3: True
tree contains 12: True
tree contains 7: False
You need a multi-parameter type class. Your current definition of Set t doesn't mention the contained type in the class definition, so the member contains has to work for any a. Try this:
class Set t a | t -> a where
contains :: (Ord a) => t-> a-> Bool
instance (Ord a) => Set (RBT a) a where
contains Leaf b = False
contains t#(Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
The | t -> a bit of the definition is a functional dependency, saying that for any given t there is only one possible a. It's useful to have (when it makes sense) since it helps the compiler figure out types and reduces the number of ambiguous type problems you often otherwise get with multi-parameter type classes.
You'll also need to enable the language extensions MultiParamTypeClasses and FunctionalDependencies at the top of your source file:
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
The error means that the types don't match. What is the type of contains? (If its type is not something like t -> a -> Bool as set_contains is, something is wrong.)
Why do you think you shouldn't roll your own classes?
When you write the instance for Set (RBT a), you define contains for the specific type a only. I.e. RBT Int is a set of Ints, RBT Bool is a set of Bools, etc.
But your definition of Set t requires that t be a set of all ordered a's at the same time!
That is, this should typecheck, given the type of contains:
tree :: RBT Bool
tree = ...
foo = contains tree 1
and it obviously won't.
There are three solutions:
Make t a type constructor variable:
class Set t where
contains :: (Ord a) => t a -> a-> Bool
instance Set RBT where
...
This will work for RBT, but not for many other cases (for example, you may want to use a bitset as a set of Ints.
Functional dependency:
class (Ord a) => Set t a | t -> a where
contains :: t -> a -> Bool
instance (Ord a) => Set (RBT a) a where
...
See GHC User's Guide for details.
Associated types:
class Set t where
type Element t :: *
contains :: t -> Element t -> Bool
instance (Ord a) => Set (RBT a) where
type Element (RBT a) = a
...
See GHC User's Guide for details.
To expand on Ganesh's answer, you can use Type Families instead of Functional Dependencies. Imho they are nicer. And they also change your code less.
{-# LANGUAGE FlexibleContexts, TypeFamilies #-}
class Set t where
type Elem t
contains :: (Ord (Elem t)) => t -> Elem t -> Bool
instance (Ord a) => Set (RBT a) where
type Elem (RBT a) = a
contains Leaf b = False
contains (Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b