今天我用 Haskell 写了第一个程序。编译并运行成功。而且由于它不是典型的“你好世界”程序,它实际上做的远不止这些,所以请祝贺我:D
不管怎样,我对我的代码和 Haskell 中的语法没有什么疑问。
Problem:
我的程序读取一个整数N
从标准输入,然后,对于每个整数i
在范围中[1,N]
,它打印是否i
是否是质数。目前它不检查输入错误。 :-)
解决方案:(也有疑问/问题)
为了解决这个问题,我编写了这个函数来测试整数的素数:
is_prime :: Integer -> Bool
is_prime n = helper n 2
where
helper :: Integer -> Integer -> Bool
helper n i
| n < 2 * i = True
| mod n i > 0 = helper n (i+1)
| otherwise = False
效果很好。但我怀疑第一行是多次尝试的结果,正如我在本教程没有工作,并给出了这个错误(我suppose这是一个错误,尽管它没有这么说):
prime.hs:9:13:
Type constructor `Integer' used as a class
In the type signature for `is_prime':
is_prime :: Integer a => a -> Bool
根据教程(顺便说一句,这是一个写得很好的教程),第一行应该是:(教程说(Integral a) => a -> String
, 所以我认为(Integer a) => a -> Bool
应该也能工作。)
is_prime :: (Integer a) => a -> Bool
这不起作用,并给出上面发布的错误(?)。
为什么它不起作用?这条线(不起作用)和这条线(起作用)有什么区别?
另外,循环的惯用方法是什么1
to N
?我对代码中的循环并不完全满意。请提出改进建议。这是我的代码:
--read_int function
read_int :: IO Integer
read_int = do
line <- getLine
readIO line
--is_prime function
is_prime :: Integer -> Bool
is_prime n = helper n 2
where
helper :: Integer -> Integer -> Bool
helper n i
| n < 2 * i = True
| mod n i > 0 = helper n (i+1)
| otherwise = False
main = do
n <- read_int
dump 1 n
where
dump i x = do
putStrLn ( show (i) ++ " is a prime? " ++ show (is_prime i) )
if i >= x
then putStrLn ("")
else do
dump (i+1) x