在Haskell 中的默认功能组合问题的评论中,人们提到为 制作一个Num
实例a -> r
,所以我想我会尝试使用函数符号来表示乘法:
{-# LANGUAGE TypeFamilies #-}
import Control.Applicative
instance Show (a->r) where -- not needed in recent GHC versions
show f = " a function "
instance Eq (a->r) where -- not needed in recent GHC versions
f == g = error "sorry, Haskell, I lied, I can't really compare functions for equality"
instance (Num r,a~r) => Num (a -> r) where
(+) = liftA2 (+)
(-) = liftA2 (-)
(*) = liftA2 (*)
abs = liftA abs
negate = liftA negate
signum = liftA signum
fromInteger a = (fromInteger a *)
请注意,fromInteger 定义意味着我可以写出3 4
12 和7 (2+8)
70 的值,正如您所希望的那样。
然后一切都变得奇妙,有趣而奇怪!如果可以的话,请解释这种奇怪:
*Main> 1 2 3
18
*Main> 1 2 4
32
*Main> 1 2 5
50
*Main> 2 2 3
36
*Main> 2 2 4
64
*Main> 2 2 5
100
*Main> (2 3) (5 2)
600
[编辑:使用 Applicative 而不是 Monad,因为 Applicative 通常很棒,但它对代码没有太大影响。]