函数在Haskell中重载 [英] Function Overloading in Haskell

查看:462
本文介绍了函数在Haskell中重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构体,它代表 mx + b 形式的线的方程和一个点的结构

 行{m :: Double,b :: Double}派生(Show,Eq)
Point {x :: Double,y :: Double}派生(Show ,Eq)

我希望函数垂直这样做:

  vertical(Line mb)(Point xy)= 
Line m2 b2其中
m2 =( - 1 / m)
b2 = y - m2 * x

if给定一条线和一个点,或者一个部分应用的线

 垂直线(线mb)= 
线m2其中
m2 =(-1 / m)

如果只有一条线。



这里的问题是,我得到


垂直的方程式具有不同数量的参数



解决方案

在第一种情况下,您希望 vertical 类型为 Line - >点 - > Line ,而在第二种情况下,您希望它的类型为 Line - >双 - >线。这表明我们可以用一个类型类来完成这个工作,我们可以抽象出第二个参数的类型:

pre code> class Perpendicular a where
perpendicular :: Line - > a - >行

您的第一个案例将成为 Point

 实例垂直点其中
垂直(直线mb)(点xy)=直线m2 b2
其中m2 =(-1 / m)
b2 = y - m2 * x

而第二个变为 Double的实例。

 实例Perpendicular Double where 
vertical(Line mb)= Line m2
其中m2 =(-1 / m)


I have a structure which represents the equation of a line in the form m x + b and a structure of a point

Line { m :: Double, b :: Double } deriving( Show, Eq )
Point { x :: Double, y :: Double } deriving( Show, Eq )

I want the function perpendicular that does the following:

perpendicular (Line m b) (Point x y) = 
        Line m2 b2 where
                m2 = (-1/m)
                b2 = y - m2*x

if given a line and a point, or a partially applied Line

perpendicular (Line m b) = 
        Line m2 where
                m2 = (-1/m)

if only given a Line.

The problem here is that I get

Equations for `perpendicular' have different numbers of arguments

解决方案

In the first case, you want the type of perpendicular to be Line -> Point -> Line, while in the second case you want it to have the type Line -> Double -> Line. This suggests that we can do this with a type class where we abstract over the type of the second argument:

class Perpendicular a where
  perpendicular :: Line -> a -> Line

Your first case then becomes an instance for Point

instance Perpendicular Point where
  perpendicular (Line m b) (Point x y) = Line m2 b2
    where m2 = (-1/m)
          b2 = y - m2*x

while the second becomes an instance for Double.

instance Perpendicular Double where
  perpendicular (Line m b) = Line m2
    where m2 = (-1/m)

这篇关于函数在Haskell中重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆