使数字函数成为Num的一个实例? [英] Making numeric functions an instance of Num?

查看:127
本文介绍了使数字函数成为Num的一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用二元运算符在haskell中编写数值函数。所以,例如,用一元数字函数:

I want to be able to compose numeric functions in haskell using binary operators. So, for example, with unary numeric functions:

f*g

应该转化为:

should translate to:

\x -> (f x)*(g x)

以及类似的加法。让你自己的操作员做这件事很简单,但我真的很想让 Num a => a - >一个函数的Num实例,但我不知道如何做到这一点。

and similarly for addition. Making your own operator to do this is pretty straightforward, but I'd really like to just make Num a => a -> a functions an instance of Num, but I'm not sure how to do so.

我也想使这个arity通用,但是在Haskell中构造泛型函数的难度可能会比较大,所以定义单独的 Num a => a - > a - > a Num a => a - > a - > a - >一个,等等...实例达到一些相当大的数目。

I'd also like to make this arity generic, but that might be too much trouble for how difficult it is to do arity generic functions in Haskell, so it might just be better to define seperate Num a => a -> a -> a, Num a => a -> a -> a -> a, etc... instances up to some reasonably large number.

推荐答案

arity

an instance with generic arity

instance Num b => Num (a->b) where
    f + g = \x -> f x + g x
    f - g = \x -> f x - g x
    f * g = \x -> f x * g x
    negate f = negate . f
    abs f = abs . f
    signum f = signum . f
    fromInteger n = \x -> fromInteger n

编辑:正如Christian Conkle指出的那样,这种方法存在问题。如果您打算将这些实例用于任何重要的事情或只是想了解这些问题,则应该阅读他提供的资源并自行决定是否符合您的需求。我的目的是提供一种简单的方法来使用自然符号和尽可能简单的实现来使用数字函数。

As Christian Conkle points out, there are problems with this approach. If you plan to use these instances for anything important or just want to understand the issues, you should read the resources he provided and decide for yourself whether this fits your needs. My intention was to provide an easy way to play with numeric functions using natural notation with as simple an implementation as possible.

这篇关于使数字函数成为Num的一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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