Creating a Coordinate class in Haskell

ε祈祈猫儿з 提交于 2019-12-25 13:20:46

问题


I'm attempting to add two polymorphic tuples together in a pairwise manner. (The types of the first element in one tuple should be the same as the first in the second and likewise for the second element) Here's my code:

module Main where

class Coordinate a where

    createCoordinate :: a

    getFirst :: (a,b) -> a

    getSecond :: (a,b) -> b

    addCoordinates :: (a,b) -> (a,b) -> (a,b)

instance Coordinate () where

    createCoordinate = ()

    getFirst (a,b) = a

    getSecond (a,b) = b

    addCoordinates a b = (getFirst a + getFirst b, getSecond a + getSecond b)

So, the problem is with my addCoordinates function. I was wondering if anyone could offer me any help with how to go about implementing the function. Thanks! :)


回答1:


You probably want a data type, not a class:

data Coordinate a b = Coordinate { getFirst :: a, getSecond :: b }
    deriving (Eq, Ord, Show)

Your functions would then become:

createCoordinate :: a -> b -> Coordinate a b
createCoordinate a b = Coordinate a b

addCoordinates :: (Num a, Num b) => Coordinate a b -> Coordinate a b -> Coordinate a b
addCoordinates (Coordinate a1 b1) (Coordinate a2 b2) = Coordinate (a1+a2) (b1+b2)

Note that a and b can be of any type, but addCoordinates only works if they are instances of Num, because we wish to apply + to them. You do not need a typeclass to define Coordinate.

A typeclass would allow you to define things that can be initialized to default values for instance:

class DefaultInitializable a where
    defaultInit :: a

We can then make Int an instance of this class:

instance DefaultInitializable Int where
    defaultInit = 0

And we can make Coordinate an instance as long as its parameters are also instances:

instance (DefaultInitializable a, DefaultInitializable b) => DefaultInitializable (Coordinate a b) where
    defaultInit = Coordinate default default



回答2:


I feel this might be a solution to what I wanted

module Main where

class Coordinate c where

    createCoordinate :: x -> y -> c x y

    getFirst :: c x y -> x

    getSecond :: c x y -> y

    addCoordinates :: (Num x) => (Num y) => c x y -> c x y -> c x y

instance Coordinate (,) where

    createCoordinate a b = (a,b)

    getFirst (a,_) = a

    getSecond (_,b) = b

    addCoordinates a b = (getFirst a + getFirst b, getSecond a + getSecond b)


来源:https://stackoverflow.com/questions/40822310/creating-a-coordinate-class-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!