在Tacit function composition in 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,就像您希望的那樣。
然後這一切都變得奇妙,有趣怪異!請解釋這個wierdness如果可以的話:
*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
[編輯:使用應用型的,而不是由於Monad的是應用型通常很大,但它並沒有太大的差別在所有代碼]
在GHC 7.4中,可以刪除虛擬'Show'和'Eq'實例,因爲'Num'不再需要它們。 – sdcvvc
'Monad'在這裏矯枉過正。更簡單和更通用的「應用程序」就足夠了。 – Conal
@sdcvvc我很快就會升級,是的。 – AndrewC