Vì vậy, tôi đang chơi xung quanh với điều này:Bắt một giá trị kiểu Integral a => [a] từ một giá trị của một Integral => ([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)
Và trong khi tôi có abundants_perfects_deficients
, tôi muốn có ba giá trị: abundants
, perfects
và deficients
tất cả các loại Integral a -> [a]
.
Một điều đó không làm việc là:
abundants,perfects,deficients :: Integral a => [a]
(abundants,perfects,deficients) = abundants_perfects_deficients
Bởi vì đây chế các ba cho tất cả được so với cùng a
.
tôi đã cố gắng một cái gì đó để làm cho họ một-by-một, vì vậy họ sẽ không lẫn nhau hạn chế, nhưng điều đó không làm việc, hoặc:
perfects :: Integral a => [a]
(_,perfects,_) = abundants_perfects_deficients
Bởi vì trình biên dịch không thể tìm ra cách để chuyển đổi giá trị loại forall a. Integral a => ([a],[a],[a])
để nhập (t1, forall a. Integral a => [a], t2)
.
Điều đó có vẻ đủ sắc sảo.
Bây giờ tôi biết tôi có thể thực hiện chúng một cách riêng biệt (chỉ perfects = filter isPerfect [1..]
), hoặc hạn chế chúng để tất cả có cùng loại ((abundants,perfects,deficients) = abundants_perfects_deficients
hoạt động tốt nếu abundants,perfects,deficients :: [Integer]
), nhưng
- Tôi thích sử dụng chia sẻ thông tin để xây dựng cả ba
- tôi muốn không chỉ bị hạn chế để
Integer
s
ý tưởng?
Sửa: Fascinatingly đủ công trình này:
abundants :: Integral a => [a]
abundants = f as
where as :: [Integer]
(as,_,_) = abundants_perfects_deficients
f :: Integral a => [Integer] -> [a]
f = map fromInteger
Nhưng điều này không:
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'
Tôi không có ý tưởng tại sao.
sẽ không làm việc: 'fst :: (a, b) -> a' (và tương tự cho snd), bạn sẽ phải cung cấp một số truy cập ba-tuple mới;) –
Ops, bạn nói đúng. Đã cập nhật để khắc phục. – nulvinge
cần phải loại bỏ toán tử (.) Của bạn (abundants_perfects_deficients không phải là một hàm) – rampion