所以我玩这个周围:获取型积分一个的值=>并[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