Haskell 中函数的意外输出
Unexpected output from function in Haskell
我有这个函数,它接受一个整数 n,returns 整数的个数小于
n 与 n 互质。我不知道我的代码可能在哪里失败,因为我想我检查了它工作所需的一切。
我希望得到这样的输出:
eTotient 73 = 72
但我有一个看起来像这样的:
eTotient 73 = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72]
这是我的代码:
divisorCoPrime :: Int -> [Maybe Int]
divisorCoPrime n = divisorCoPrime2 n n
divisorCoPrime2 :: Int -> Int -> [Maybe Int]
divisorCoPrime2 n 1 = []
divisorCoPrime2 n x
| divides n x && isPrime x = Just x:divisorCoPrime2 n (x-1)
| otherwise = divisorCoPrime2 n (x-1)
isCoprime :: Int -> Int -> Bool
isCoprime x y = isCoprime2 (divisorCoPrime x) (divisorCoPrime y)
isCoprime2 :: [Maybe Int] -> [Maybe Int] -> Bool
isCoprime2 [] y = True
isCoprime2 x [] = True
isCoprime2 (x:xs) y
| foldl (||) False (map (x==) y) = False
| otherwise = isCoprime2 xs y
eTotient :: Int -> [Int]
eTotient n = filter (isCoprime n ) [2..(n-1)]
根据Wikipedia:
Euler's totient function [which is what I'm guessing eTotient
is supposed to be] counts the positive integers up to a given integer n
that are relatively prime to n
filter (isCoprime n ) [2..(n-1)]
是此类整数的 list,但您想要这些整数的 number - length 列表。假设其余代码是正确的,它看起来像这样:
eTotient :: Int -> Int
eTotient n = length $ filter (isCoprime n ) [2..(n-1)]
我有这个函数,它接受一个整数 n,returns 整数的个数小于 n 与 n 互质。我不知道我的代码可能在哪里失败,因为我想我检查了它工作所需的一切。
我希望得到这样的输出:
eTotient 73 = 72
但我有一个看起来像这样的:
eTotient 73 = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72]
这是我的代码:
divisorCoPrime :: Int -> [Maybe Int]
divisorCoPrime n = divisorCoPrime2 n n
divisorCoPrime2 :: Int -> Int -> [Maybe Int]
divisorCoPrime2 n 1 = []
divisorCoPrime2 n x
| divides n x && isPrime x = Just x:divisorCoPrime2 n (x-1)
| otherwise = divisorCoPrime2 n (x-1)
isCoprime :: Int -> Int -> Bool
isCoprime x y = isCoprime2 (divisorCoPrime x) (divisorCoPrime y)
isCoprime2 :: [Maybe Int] -> [Maybe Int] -> Bool
isCoprime2 [] y = True
isCoprime2 x [] = True
isCoprime2 (x:xs) y
| foldl (||) False (map (x==) y) = False
| otherwise = isCoprime2 xs y
eTotient :: Int -> [Int]
eTotient n = filter (isCoprime n ) [2..(n-1)]
根据Wikipedia:
Euler's totient function [which is what I'm guessing
eTotient
is supposed to be] counts the positive integers up to a given integern
that are relatively prime ton
filter (isCoprime n ) [2..(n-1)]
是此类整数的 list,但您想要这些整数的 number - length 列表。假设其余代码是正确的,它看起来像这样:
eTotient :: Int -> Int
eTotient n = length $ filter (isCoprime n ) [2..(n-1)]