typeclasses, overloading and instance declaration - haskell

Having this:
data Rectangle = Rectangle Height Width
data Circle = Circle Radius
class Shape a where
area :: a -> Float
perimeter :: a -> Float
instance Shape Rectangle where
area (Rectangle h w) = h * w
perimeter (Rectangle h w) = 2*h+w*2
instance Shape Circle where
area (Circle r) = pi * r**2
perimeter (Circle r) = 2*pi*r
volumenPrism base height = (area base) * height
surfacePrism shape h = (area shape) * 2 + perimeter shape * h
Why cant I write this? a is a type so why doesn't this work?
instance (Shape a) => Eq a where
x==y = area x == area y
Obviously doing like this:
instance Eq Circle where
x==y = area x == area y
first for Circle and then for Rectangle works..but it seems not the right way.
What is it I don't get in all this?
Ty

The fundamental problem is that the type class instance resolution machinery doesn't backtrack. So if you write instance Shape a => Eq a, then whenever the compiler wants to find an Eq instance, the compiler will try to use this instance and for most types it won't work out because they aren't instances of Shape.
If you still really want to do this, you can add
{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
at the top of your source file.
You can also work round some of the problems described above by also adding OverlappingInstances to the set of LANGUAGE pragmas, but you will still have a global instance for Eq that will cause significant confusion elsewhere in your program.
It's much better to just enumerate the instances you really need, even if it seems ugly. You can keep the boilerplate to a minimum with a helper function, e.g.
x `areaEq` y = area x == area y
and then
instance Eq Circle where
(==) = areaEq
etc.

Related

Haskell Translation Task

I'm new to programming, and I'm having trouble solving a task.
I have to use the function. In that case I have to implement it on a triangle.
I've tried different things but I'm just getting errors and that's why I'd like to ask for help.
data Triangle = Triangle {
tP1 :: Point,
tP2 :: Point,
tP3 :: Point}
deriving (Show)
First, points and vectors are two separate concepts, and should probably be distinct types, not just two different aliases for a 2-tuple.
data Point = Pt Float Float
data Vector = V Float Float
Second, your type class seems to capture the idea of translating collections of points using the same vector. The return type should then be the same as the first argument type, not hard-coded to Point.
class Polygon p where
translatePol :: p -> VectorD -> p
Now you can start simple, and define a Polygon instance for Point. (Think of a point as a degenerate polygon.)
instance Polygon Point where
translatePol (Pt x y) (Mvector v1 v2) = Pt (x + v1) (y + v2)
This can be used to define the instance for Triangle more simply.
instance Polygon Triangle where
translatePol (MTriangle p1 p2 p3) v = MTriangle (t p1) (t p2) (t p3)
where t p = translatePol p v

Type class instance with more restrictive signature

Let's say I'm writing a data type to represent a coordinate in a cartesian coordinate system. I'd like to define functions on that data type and use Haskell type checking to prevent mixing up numbers that lie on x axis with the numbers on the y axis.
Here's the data type definition, with a phantom type that tracks the coordinate axis and two functions to construct the values:
data X
data Y
newtype Coordinate axis = Coordinate Int64 deriving (Show)
newX :: Int64 -> Coordinate X
newX = Coordinate
newY :: Int64 -> Coordinate Y
newY = Coordinate
Let's define a sliding function that slides the coordinate, either by Int value or another Coordinate value. In the first case the coordinate should keep its axis and in the second case both arguments should have the same axis:
slideByInt :: Coordinate a -> Int64 -> Coordinate a
slideByInt (Coordinate x) y = Coordinate $ x + y
slideByCoord :: Coordinate a -> Coordinate a -> Coordinate a
slideByCoord (Coordinate x) (Coordinate y) = Coordinate (x + y)
This all works great and it prevents me from confusing X and Y axis in functions that manipulate Coordinates.
My question is: how would I wrap slideByInt and slideByCoord functionality behind a class, so that I can have just with the slide function. This compiles:
class Slide a where
slide :: Coordinate x -> a -> Coordinate x
instance Slide Int64 where
slide (Coordinate x) y = Coordinate (x + y)
instance Slide (Coordinate x) where
slide (Coordinate x) (Coordinate y) = Coordinate (x + y)
but it's not as type safe as the standalone functions: slide (newX 1) (newY 1) should not type check! How would one go about fixing this, in a sense, how can I make the instance for two Coordinates less permissive than it is?
I've tried with a bunch of extensions (InstanceSigs, FunctionalDependencies, type constraints...) but nothing compiles and it's hard to tell if that's the wrong way completely or I just have to tweak my code a little bit.
Thanks...
Consider what this class declaration is stating:
class Slide a where
slide :: Coordinate x -> a -> Coordinate x
for any type x, an instance of Slide promises that given a Coordinate x and an a, it will give you back a Coordinate x. Right there is your problem. You don't want any x all the time.
I think the easiest way to achieve what you want is with a second type class parameter for the coordinate type:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
class Slide x a where
slide :: Coordinate x -> a -> Coordinate x
instance Slide X Int64 where
slide = slideByInt
instance Slide Y Int64 where
slide = slideByInt
instance Slide X (Coordinate X) where
slide = slideByCoord
instance Slide Y (Coordinate Y) where
slide = slideByCoord
The last two instances can actually be replaced with this more general instance:
{-# LANGUAGE TypeFamilies #-}
instance (a ~ b) => Slide a (Coordinate b) where
slide = slideByCoord
For what it's worth, I like to avoid using typeclasses in this manner. I don't think the immediate convenience of overloaded functions is worth the boilerplate and long-term maintenance burden. But that's just my opinion.

Creating figures in Haskell

Im trying to create datatype "Figure" in Haskell, this datatype should have multiple values:
Square (with parameter length)
Triangle (with parameter length)
Circle (with parameter radius)
Every figure should have a color as well (let's say black and white), this is how my code currently looks like but this doesn't work.
Can anyone help me?
class Figure_ a where
perimeter :: a -> Double
area :: a -> Double
data Figure = forall a. Figure_ a => Figure a
type Radius = Double
type Side = Double
type Color = String
data Circle = Circle Radius
data Triangle = Triangle Side
data Square = Square Side
instance Figure_ Circle where
perimeter (Circle r) = 2 * pi * r
area (Circle r) = pi * r * r
instance Figure_ Triangle where
perimeter (Triangle x y) = 2*(x + y)
area (Triangle x y) = x * y
instance Figure_ Square where
perimeter (Square s) = 4*s
area (Square s) = s*s
instance Figure_ Figure where
perimeter (Figure shape) = perimeter shape
For forall use:
{-# LANGUAGE ExistentialQuantification #-}
Also, your triangle is accepting two parameters, so it should be like this:
data Triangle = Triangle Side Side
But looking at the formula of your Triangle, I think you seem to be confusing it with Rectangle. Also, indentation of your code doesn't seem to be correct. Your code should look like this:
class Figure_ a where
perimeter :: a -> Double
area :: a -> Double
The same indentation rule should also be followed when you create instance of that typeclass.
Im trying to create datatype "Figure" in Haskell, this datatype should have multiple values:
Square (with parameter length)
...
Circle (with parameter radius)
I'm leaving out the triangle to avoid thinking about geometry. Anyway, the questions sounds like you might want the following:
data Figure = Square Double | ... | Circle Double
And then you can define functions like:
area :: Figure -> Double
area (Square side) = side * side
area ... = ...
area (Circle radius) = pi * radius * radius
If you only need one datatype, you don't need classes in Haskell. Haskell classes are for having more than one datatype when they all support a common interface.
There is one reason to prefer your construction with class and forall over the otherwise simpler version with just data: In your version, it is easier to add another kind of figure that was not planned for. If you feel you need this, you might want to read about the existential typeclass antipattern. But if you're just trying to represent figures in Haskell at all, I would certainly start with a simple datatype.

What is wrong with this class/instance?

I have this:
data Vector3 t = Vector3 { ax, ay, az :: t }
data Point3 t = Point3 { x, y, z :: t }
data Ray3 t = Ray3 { ori :: Point3 t, dir :: Vector3 t }
data Sphere t = Sphere { center :: Point3 t, radius :: t }
I want a Shape type class, so I did this:
class Shape s where
distance :: s -> Ray3 t -> t
distance takes a shape and a ray and computes the distance to the shape along the given ray. When I try to create an instance, it doesn't work. This is what I have so far:
instance Shape (Sphere t) where
distance (Sphere center radius) ray = -- some value of type t --
How do I create an instance of Shape? I've tried everything I can think of, and I'm getting all kind of errors.
The problem is that the type variable t in Sphere t is not the same as the one in the type signature of distance. Your current types are saying that if I have a Sphere t1, I can check it against a Ray3 t2. However, you probably want these to be the same type. To solve this, I would change the Shape class to
class Shape s where
distance :: s t -> Ray3 t -> t
Now the dependency on t is explicit, so if you write your instance as
instance Shape Sphere where
distance (Sphere center radius) ray = ...
the types should line up nicely, although you'll probably need to add in some numeric constraints on t to do any useful calculations.

haskell polymorphism and lists

Suppose I have the following:
class Shape a where
draw a :: a -> IO ()
data Rectangle = Rectangle Int Int
instance Shape Rectangle where
draw (Rectangle length width) = ...
data Circle = Circle Int Int
instance Shape Circle where
draw (Circle center radius) = ...
Is there any way for me to define a list of shapes, traverse over the list, and call the draw function on each shape? The following code won't compile because the list elements aren't all the same type:
shapes = [(Circle 5 10), (Circle 20, 30), (Rectangle 10 15)]
I know I'm thinking in an OO way and trying to apply it to Haskell, and that might not be the best approach. What would be the best Haskell approach for programs that need to deal with collections of different types of objects?
If you really do need to do this, then use an existential:
{-# LANGUAGE GADTs #-}
class IsShape a where
draw :: a -> IO ()
data Rectangle = Rectangle Int Int
instance IsShape Rectangle where
draw (Rectangle length width) = ...
data Circle = Circle Int Int
instance IsShape Circle where
draw (Circle center radius) = ...
data Shape where
Shape :: IsShape a => a -> Shape
shapes = [Shape (Circle 5 10), Shape (Circle 20 30), Shape (Rectangle 10 15)]
(I renamed your class as there would be a name clash with the datatype otherwise, and having the naming this way round seems more natural).
The advantage of this solution over the other answer involving a single datatype with different constructors is that it is open; you can define new instances of IsShape wherever you like. The advantage of the other answer is that it's more "functional", and also that the closedness may in some cases be an advantage as it means that clients know exactly what to expect.
Consider using a single type instead of separate types and a typeclass.
data Shape = Rectangle Int Int
| Circle Int Int
draw (Rectangle length width) = ...
draw (Circle center radius) = ...
shapes = [Circle 5 10, Circle 20 30, Rectangle 10 15]
One way to do it would be with vtables:
data Shape = Shape {
draw :: IO (),
etc :: ...
}
rectangle :: Int -> Int -> Shape
rectangle len width = Shape {
draw = ...,
etc = ...
}
circle :: Int -> Int -> Shape
circle center radius = Shape {
draw = ...,
etc = ...
}
As Ganesh said, you could indeed use GADTs to have more type safety. But if you don't want (or need) to, here's my take on this:
As you already know, all elements of a list need to be of the same type. It isn't very useful to have a list of elements of different types, because then your throwing away your type information.
In this case however, since you want throw away type information (you're just interested in the drawable part of the value), you would suggest to change the type of your values to something that is just drawable.
type Drawable = IO ()
shapes :: [Drawable]
shapes = [draw (Circle 5 10), draw (Circle 20 30), draw (Rectangle 10 15)]
Presumably, your actual Drawable will be something more interesting than just IO () (maybe something like: MaxWidth -> IO ()).
And also, due to lazy evaluation, the actual value won't be drawn until you force the list with something like sequence_. So you don't have to worry about side effects (but you probably already saw that from the type of shapes).
Just to be complete (and incorporate my comment into this answer): This is a more general implementation, useful if Shape has more functions:
type MaxWith = Int
class Shape a where
draw :: a -> MaxWidth -> IO ()
size :: a -> Int
type ShapeResult = (MaxWidth -> IO (), Int)
shape :: (Shape a) => a -> ShapeResult
shape x = (draw x, size x)
shapes :: [ShapeResult]
shapes = [shape (Circle 5 10), shape (Circle 20 30), shape (Rectangle 10 15)]
Here, the shape function transforms a Shape a value into a ShapeResult value, by simply calling all the functions in the Shape class. Due to laziness, none of the values are actually computed until you need them.
To be honest, I don't think I would actually use a construct like this. I would either use the Drawable-method from above, or if a more general solution is needed, use GADTs. That being said, this is a fun exercise.
How to deal with a heterogeneous list of shapes in Haskell — Abstract polymorphism with type classes:
http://pastebin.com/hL9ME7qP via #pastebin
CODE:
{-# LANGUAGE GADTs #-}
class Shape s where
area :: s -> Double
perimeter :: s -> Double
data Rectangle = Rectangle {
width :: Double,
height :: Double
} deriving Show
instance Shape Rectangle where
area rectangle = (width rectangle) * (height rectangle)
perimeter rectangle = 2 * ((width rectangle) + (height rectangle))
data Circle = Circle {
radius :: Double
} deriving Show
instance Shape Circle where
area circle = pi * (radius circle) * (radius circle)
perimeter circle = 2.0 * pi * (radius circle)
r=Rectangle 10.0 3.0
c=Circle 10.0
list=[WrapShape r,WrapShape c]
data ShapeWrapper where
WrapShape :: Shape s => s -> ShapeWrapper
getArea :: ShapeWrapper -> Double
getArea (WrapShape s) = area s
getPerimeter :: ShapeWrapper -> Double
getPerimeter (WrapShape s) = perimeter s
areas = map getArea list
perimeters = map getPerimeter list
A variant of Ganesh's solution using the existential quantification syntax instead.
{-# LANGUAGE ExistentialQuantification #-}
class IsShape a where
draw :: a -> String
data Rectangle = Rectangle Int Int
instance IsShape Rectangle where
draw (Rectangle length width) = ""
data Circle = Circle Int Int
instance IsShape Circle where
draw (Circle center radius) = ""
data Shape = forall a. (IsShape a) => Shape a
shapes = [Shape (Circle 5 10), Shape (Circle 20 30), Shape (Rectangle 10 15)]

Resources