所以我玩這個周圍:獲取型積分一個的值=>並[a]從一個積分的值=>([A],[A],[A])
factors :: Integral a => a -> [a]
factors n = filter (\d -> n `rem` d == 0) . takeWhile (\d -> d*d <= n) $ [ 1 .. ]
abundants_perfects_deficients :: Integral a => ([a],[a],[a])
abundants_perfects_deficients = foldr switch ([],[],[]) [1..]
where switch :: Integral a => a -> ([a],[a],[a]) -> ([a],[a],[a])
switch n (as,ps,ds) =
let t = sum (factors n) in
if t < n then (as,ps,n:ds)
else if t == n then (as,n:ps,ds)
else (n:as,ps,ds)
雖然我有abundants_perfects_deficients
,我寧願有三個值:abundants
,perfects
和deficients
所有類型Integral a -> [a]
。
一兩件事,不工作是:
abundants,perfects,deficients :: Integral a => [a]
(abundants,perfects,deficients) = abundants_perfects_deficients
因爲這限制了三都是在同一a
。
我試圖事做他們一個接一個,所以他們不會互相制約,但沒有工作,要麼:
perfects :: Integral a => [a]
(_,perfects,_) = abundants_perfects_deficients
因爲編譯器無法弄清楚如何轉換類型forall a. Integral a => ([a],[a],[a])
的值爲(t1, forall a. Integral a => [a], t2)
。
這似乎足夠的cromulent。
現在我知道我可以單獨執行這些(只是perfects = filter isPerfect [1..]
),或將其約束到所有相同類型的((abundants,perfects,deficients) = abundants_perfects_deficients
工作正常,如果abundants,perfects,deficients :: [Integer]
),但
- 我喜歡使用共享信息來建立所有三個
- 我想不只是被限制爲
Integer
小號
想法?
編輯:讓人着迷足夠的這個作品:
abundants :: Integral a => [a]
abundants = f as
where as :: [Integer]
(as,_,_) = abundants_perfects_deficients
f :: Integral a => [Integer] -> [a]
f = map fromInteger
但這並不:
abundants_perfects_deficients' :: (Integral a,Integral p, Integral d) => ([a],[p],[d])
abundants_perfects_deficients' = (f as, f ps, f ds)
where as,ps,ds :: [Integer]
(as,ps,ds) = abundants_perfects_deficients
f :: Integral a => [Integer] -> [a]
f = map fromInteger
abundants,perfects,deficients :: (Integral a) => [a]
(abundants,perfects,deficients) = abundants_perfects_deficients'
我不知道爲什麼。
將無法正常工作:'FST ::(A,B) - >一個'(和snd類似),你將不得不提供一些新的三元組訪問器;) –
Ops,你是對的。更新以修復它。 – nulvinge
需要刪除你的(。)運算符(abundants_perfects_deficients不是函數) – rampion