2014-04-29 42 views
1

所以我需要编写一个返回整数列表的产品的程序。这是我试图做的。但每当我在第四行的=号上得到“分析错误”时。Haskell列表的产品

--product.hs 
    product :: [Integer] -> Integer 
    product []  = 1 
    product i f = foldl (*) 1 [i..f] 


    main = do 
      print "Please enter first number" 
      i <- readLn 
      print "Please enter second number" 
      f <- readLn 
     print "The result is:" 
     print (product i f) 

我也试图与

product (x:xs) = x * product xs 

,但它仍然给我解析错误=符号

+1

什么是“整数列表的产物”?我想你是说,列表中整数的乘积。 – leftaroundabout

回答

4

在下面的代码

product :: [Integer] -> Integer 
product []  = 1 
product i f = foldl (*) 1 [i..f] 

声明的product类型是[Integer] -> Integer,但在第二个条款中,您给它两个参数,这显然不符合它的类型。

您可以定义它只是像这样

product xs = foldl (*) 1 xs 

,并使用它像这样

product [i..f] 

顺便说一句,productPrelude提供的标准功能,具有类似(更好)类型和相同的功能。

+1

With _a better_type:'product :: Num a => [a] - > a'。 – leftaroundabout

+0

@leftaroundabout是的,你是对的。 –

+0

甚至无意识地用'product = foldl(*)1' – ScarletAmaranth

-2

您的分析错误可能是由于缩进不一致。一个好的建议是只使用空格来缩进。虽然可以使用制表符,但使用不按Haskell的方式精确处理制表符的编辑器很容易。

在这里,所有的函数声明都需要垂直对齐,就像do块中的所有语句一样。

+0

有趣的是,如何唯一解释实际问题的原因*问*让你失望。 (是的,我知道另一个答案解释了稍后会显示的内容,但它没有解释他们*解析错误。) –