2011-03-17 56 views
12

我一直在通過Haskell monoids and their uses,這讓我對monoids的基礎知識有了很好的理解。其中一個在博客中介紹的東西是任何幺半羣,它就像下面的用法:在Haskell中使用Maybe編寫Maximum Monoid

foldMap (Any . (== 1)) tree 
foldMap (All . (> 1)) [1,2,3] 

與此類似,我一直在努力構建一個最大的獨異,並拿出以下:

newtype Maximum a = Maximum { getMaximum :: Maybe a } 
     deriving (Eq, Ord, Read, Show) 

instance Ord a => Monoid (Maximum a) where 
     mempty = Maximum Nothing 
     [email protected](Maximum (Just x)) `mappend` Maximum Nothing = m 
     Maximum Nothing `mappend` y = y 
     [email protected](Maximum (Just x)) `mappend` [email protected](Maximum (Just y)) 
      | x > y = m 
      | otherwise = n 

我可以構建針對特定類型的最大幺 - 說民例如,很容易,但希望它是什麼(用的是什麼是奧德的實例明顯的要求)是有用的。

在這一點上我的代碼編譯,但就是這樣。如果我嘗試運行它,我得到這個:

> foldMap (Just) [1,2,3] 

<interactive>:1:20: 
    Ambiguous type variable `a' in the constraints: 
     `Num a' arising from the literal `3' at <interactive>:1:20 
     `Monoid a' arising from a use of `foldMap' at <interactive>:1:0-21 
    Probable fix: add a type signature that fixes these type variable(s) 

我不知道這是因爲我打電話錯了,還是因爲我的幺不正確,或兩者兼而有之。我很感謝任何有關我出錯的指導(包括邏輯錯誤和非慣用Haskell用法,因爲我對這門語言很陌生)。

- 編輯 -

保羅·約翰遜,在下面留言,提示可能留下了。我的第一次嘗試看起來是這樣的:

newtype Minimum a = Minimum { getMinimum :: a } 
     deriving (Eq, Ord, Read, Show) 

instance Ord a => Monoid (Minimum a) where 
     mempty = ?? 
     [email protected](Minimum x) `mappend` [email protected](Minimum y) 
      | x < y  = m 
      | otherwise = n 

但我不清楚如何表達mempty而不知道應該是什麼的mempty值。我怎麼能概括這個?

+0

我看看它是如何工作的,但爲什麼會有「也許」內的最高類型?如果你只是說「最大a」,那麼它簡化了你的實例。 「也許a」只要是「a」就是Ord的一個實例,所以你可以只說「最大(也許是整數)」,它會做正確的事情。 – 2011-03-18 09:44:52

+0

@Paul Johnson我看到你離開Maybe的原因,但我不知道如何表達。我將代碼添加到了上面的問題中,以便它更具可讀性。 – 2011-03-18 10:53:26

+2

啊,我看到你的問題。如果你添加了「Bounded」作爲約束,那麼你可以讓mempty返回Minimum的下限和Maximum的上限。否則你是正確的;對於mempty來說沒有正確的事情。這意味着這不是一個monoid。 – 2011-03-18 22:00:26

回答

12

傳遞給foldMap的函數需要返回一個獨異,在這種情況下Maximum a類型:

> foldMap (Maximum . Just) [1,2,3] 
Maximum {getMaximum = Just 3} 
+0

現在你指出了,這似乎很明顯:)謝謝你的答案! – 2011-03-17 21:17:22

+1

ala'最大foldMap只需[1,2,3] =只有3 - 給定最大的正確Newtype實例。從這個包: http://hackage.haskell.org/package/newtype – 2011-03-18 14:29:05