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

查看:28
本文介绍了使数字函数成为 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

应该翻译成:

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 中执行 arity 通用函数有多么困难,所以最好定义单独的 Num a =>->->a, Num 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.

推荐答案

具有泛型参数的实例

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天全站免登陆