문제

So I need to write a program returning the product of a list of integers.Here is what I tried to make.But every time I get "parse error"on the = sign of the 4th line.

--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)

I also tried with

    product (x:xs) = x * product xs

but it still gives me parse error on the = sign

도움이 되었습니까?

해결책

In the following code

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

you declare the type of product is [Integer] -> Integer, but in the second clause, you give it two parameters, this obviously does not match with its type.

You can define it simply like this

product xs = foldl (*) 1 xs

and use it like this

product [i..f]

By the way, product is a standard function offered by Prelude, with a similar (better) type and the same function.

다른 팁

Your parse error is probably due to inconsistent indentation. A good advice is to only use spaces for indentation. While it is possible to use tabs, it is easy to trip up with an editor that doesn't treat tabs precisely the way Haskell does.

Here, all your function declarations need to be aligned vertically, as do all the statements in your do block.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top