I've just started programming in Haskell and to get used to the syntax and general style of the language I've decided to try and solve some basic problems on Project Euler.
However, when I tried to compile my code for Problem 1 in GHC, I received an error:
main = do
sum :: Int -> Int
sum n
| n == 0 = 0
| n `mod` 3 == 0 = n + sum (n - 1)
| n `mod` 5 == 0 = n + sum (n - 1)
| otherwise = sum (n - 1)
print sum 1000
The error message in question:
Problem1.hs:5:9: error: parse error on input `|'
|
5 | | n == 0 = 0
| ^
Other users having this or a similar problem here usually had something syntactically simple wrong with their code, such as having typed == instead of =, or had an indentation error, but I don't know why my code doesn't compile properly.
I don't believe it is related to indentation; I am using VSCode and my tab size is set to 4 spaces, but I have also tried indenting manually by using space, both of which produced the same error.
As #Caramiriel rightfully corrected me, functions cannot be defined in a do-block. I solved this by simply pulling sum out of main, but this left 2 problems in the code:
The function name sum is ambiguous, as it could refer both to the automatically imported function Prelude.sum, or the one I created. To solve this, I simply changed my function name to mySum.
print mySum 1000 does not compile, as this is equivalent to print (mySum) 1000, where both mySum and 1000 are inputs for print. To fix this, I simply added parentheses: print (mySum 1000)
On a less important note, I misread the original question on Project Euler, and it should be print (mySum 999) instead. This leaves me with the following (working!) code:
mySum :: Int -> Int
mySum n
| n == 0 = 0
| n `mod` 3 == 0 = n + mySum (n - 1)
| n `mod` 5 == 0 = n + mySum (n - 1)
| otherwise = mySum (n - 1)
main = do
print (mySum 999)
Actually, functions can be defined in a do block, but you must use a let statement, so the following would work fine:
main = do
let sum :: Int -> Int
sum n
| n == 0 = 0
| n `mod` 3 == 0 = n + sum (n - 1)
| n `mod` 5 == 0 = n + sum (n - 1)
| otherwise = sum (n - 1)
print $ sum 1000
As a matter of style, though, it's unusual to define functions within a do block unless they have to be defined there (because they make reference to a variable defined within the do-block, for example), or if they're obviously utility or convenience functions that wouldn't make sense to use outside the do block.
Related
So I've been playing with Haskell the past couple of days, and I decided I'd make a basic definition of the Fibonacci sequence. So I wrote this code:
main = do
fib :: (Integral a) => Int -> Int
fib x
| x == 0 = 0
| x == 1 = 1
| x >= 2 = fib (x - 2) + fib (x - 1)
do { print (fib 5) }
And I get an error message saying:
4:17: parse error on input `|'
I suspected tab errors, so I tried every whitespace fix I could find, but I just can't find what's wrong!
EDIT: So I did what people suggested, and I have this code now:
fib :: (Integral a) => Int -> Int
main = do
fib x
| x == 0 = 0
| x == 1 = 1
| x >= 2 = fib (x - 2) + fib (x - 1)
print (fib 5)
And I'm getting the same error.
You should define fib outside of main, not inside it. And then you should remove at least one of the dos from main.
The problem is that you are trying to define the function within do block without actually using any construct for defining things (like let).
Try defining the function outside the block:
fib :: (Integral a) => Int -> Int
fib x | x == 0 = 0
| x == 1 = 1
| x >= 2 = fib (x - 2) + fib (x - 1)
main = print (fib 5)
If you insist on defining the function locally (inside the expression that is formed by statements of the do block):
main = do
let
fib :: (Integral a) => Int -> Int
fib x | x == 0 = 0
| x == 1 = 1
| x >= 2 = fib (x - 2) + fib (x - 1)
print (fib 5)
Notice how let is used to bind a new variable fib to the function you want.
You can also define fib locally to main outside of the do block. Do bear in mind that do is syntactic sugar for the use of various monadic binding functions, and so the syntax accepted within it is not quite the same as that accepted outside it. And, in fact, your main doesn't even require the do block because you just call print rather than chaining any IO actions together.
main = let
fib x | x == 0 = 0
| x == 1 = 1
| x >= 2 = fib (x - 2) + fib (x + 1)
in
print (fib 5)
Or you could use where:
main = print (fib 5)
where
fib x | x == 0 = 0
| x == 1 = 1
| x >= 2 = fib (x - 2) + fib (x + 1)
They're the same, the question is just where the local binding actually goes. let..in gives you a new block where the new bindings are in scope, while where makes its bindings available in the scope of the function it's attached to.
If, as seems eventually likely, you do want a do block as well so you can do multiple IO actions, you can just put that in place of the call to print, like so:
main = let
fib x | x == 0 = 0
| x == 1 = 1
| x >= 2 = fib (x - 2) + fib (x + 1)
in
do print (fib 5)
print (fib 6)
I was reading the Haskell Prelude and finding it pretty understandable, then I stumbled upon the exponention definition:
(^) :: (Num a, Integral b) => a -> b -> a
x ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n where
g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
_ ^ _ = error "Prelude.^: negative exponent"
I do not understand the need for two nested wheres.
What I understood so far:
(^) :: (Num a, Integral b) => a -> b -> a
The base must be a number and the exponent intege, ok.
x ^ 0 = 1
Base case, easy.
g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
Exponention by squaring... kind of ... Why is the f helper needed? Why are f and g given single letter names? Is it just optimization, am I missing something obvious?
_ ^ _ = error "Prelude.^: negative exponent"
N > 0 was checked before, N is negative if we arrived here, so error.
My implementation would be a direct translation to code of:
Function exp-by-squaring(x, n )
if n < 0 then return exp-by-squaring(1 / x, - n );
else if n = 0 then return 1; else if n = 1 then return x ;
else if n is even then return exp-by-squaring(x * x, n / 2);
else if n is odd then return x * exp-by-squaring(x * x, (n - 1) / 2).
Pseudocode from wikipedia.
To illustrate what #dfeuer is saying, note that the way f is written it either:
f returns a value
or, f calls itself with new arguments
Hence f is tail recursive and therefore can easily be transformed into a loop.
On the other hand, consider this alternate implementation of exponentiation by squaring:
-- assume n >= 0
exp x 0 = 1
exp x n | even n = exp (x*x) (n `quot` 2)
| otherwise = x * exp x (n-1)
The problem here is that in the otherwise clause the last operation performed is a multiplication. So exp either:
returns 1
calls itself with new arguments
calls itself with some new arguments and multiplies the result by x.
exp is not tail recursive and therefore cannot by transformed into a loop.
f is indeed an optimization. The naive approach would be "top down", calculating x^(n `div` 2) and then squaring the result. The downside of this approach is that it builds a stack of intermediate computations. What f lets this implementation do is to first square x (a single multiplication) and then raise the result to the reduced exponent, tail recursively. The end result is that the function will likely operate entirely in machine registers. g seems to help avoid checking for the end of the loop when the exponent is even, but I'm not really sure if it's a good idea.
As far as I understand it exponentiation is solved by squaring as long as the exponent is even.
This leads to the answer why f is needed in case of an odd number - we use f to return the result in the case of g x 1, in every other odd case we use f to get back in the g-routine.
You can see it best I think if you look at an example:
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n
where g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
2^6 = -- x = 2, n = 6, 6 > 0 thus we can use the definition
f 2 (6-1) 2 = f 2 5 2 -- (*)
= g 2 5 -- 5 is odd we are in the "otherwise" branch
= f 2 4 (2*2) -- note that the second '2' is still in scope from (*)
= f 2 4 (4) -- (**) for reasons of better readability evaluate the expressions, be aware that haskell is lazy and wouldn't do that
= g 2 4
= g (2*2) (4 `quot` 2) = g 4 2
= g (4*4) (2 `quot` 2) = g 16 1
= f 16 0 (16*4) -- note that the 4 comes from the line marked with (**)
= f 16 0 64 -- which is the base case for f
= 64
Now to your question of using single letter function names - that's the kind of thing you have to get used to it is a way most people in the community write. It has no effect on the compiler how you name your functions - as long as they start with a lower case letter.
As others noted, the function is written using tail-recursion for efficiency.
However, note that one could remove the innermost where while preserving tail-recursion as follows: instead of
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n
where g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
we can use
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y | even n = f (x*x) (n `quot` 2) y
| otherwise = f x (n-1) (x*y)
which is also arguably more readable.
I have however no idea why the authors of the Prelude chose their variant.
I have been at this for a long time, I cant figure out whats wrong
Haskell just makes me feel so dumb
data Operation
= Nth Integer
fib :: (Integral i, Integral j) => i -> j
fib n | n == 0 = 1
| n == 1 = 1
| n == 2 = 1
| n == 3 = 1
| otherwise = (fib(n-1)+fib(n-2))* fib(n-3) `div` fib(n-4)
main = do
command <- getLine
case command of
Nth op -> show $ fib op
Nothing -> "Invalid operation"
So when the user inputs Nth 9, the fib function needs to get called with n=9 and give the output to the user. I feel like my case control structure is appropriate, but I cant get it to work at all!!!
you are almost complete.
use deriving (Read) for reading String as Operation.
http://en.wikibooks.org/wiki/Haskell/Classes_and_types#Deriving
If you want to handle read error, see How to catch a no parse exception from the read function in Haskell?
data Operation = Nth Integer deriving (Read)
fib :: (Integral i, Integral j) => i -> j
fib n | n == 0 = 1
| n == 1 = 1
| n == 2 = 1
| n == 3 = 1
| otherwise = (fib(n-1)+fib(n-2))* fib(n-3) `div` fib(n-4)
main = do
command <- getLine
print $ case read command of
Nth op -> fib op
I want to refresh a variable value, each time I make a recursion of a function. To make it simple I will give you an example.
Lets say we give to a function a number (n) and it will return the biggest mod it can have, with numbers smaller of itself.
{- Examples:
n=5 `mod` 5
n=5 `mod` 4
n=5 `mod` 3
n=5 `mod` 2
n=5 `mod` 1
-}
example :: Integer -> Integer
example n
| n `mod` ... > !The biggest `mod` it found so far! && ... > 0
= !Then the biggest `mod` so far will change its value.
| ... = 0 !The number we divide goes 0 then end! = 0
Where ... = recursion ( I think)
I don't know how I can describe it better. If you could help me it would be great. :)
You can write it as you described:
example :: Integer -> Integer
example n = biggestRemainder (abs n) 0
where
biggestRemainder 0 biggestRemainderSoFar = biggestRemainderSoFar
biggestRemainder divisor biggestRemainderSoFar = biggestRemainder (divisor - 1) newBiggestRemainder
where
thisRemainder = n `mod` divisor
newBiggestRemainder = case thisRemainder > biggestRemainderSoFar of
True -> thisRemainder
False -> biggestRemainderSoFar
This function can also be written more easily as
example2 :: Integer -> Integer
example2 0 = 0
example2 n = maximum $ map (n `mod`) [1..(abs n)]
I need to implement a recursive function that returns 1 if the number is prime or 0 otherwise. The homework problem says that I can't use '%' mod. Haskell should be something like this... I'm not sure.
isprime x = prime(x sqrt(x))
prime x i = | i==1 = 1
| mod(x i)==0 = 0
| otherwise = prime(x i-1)
mod num div | num<div = n
| otherwise = mod(num-div div)
I tested an algorithm in C because I don't have a Haskell compiler on my Mac, but there's something wrong because it's returning false positive on primes-1. idk why.
int main (int argc, const char * argv[]){
int a=0,b=31;
printf("\n Prime numbers between %d and %d \n",a,b);
for(int a=0; a<=b; a++){
if(isPrime(a)==0){
printf("%d, ",a);
}
}
return 0;
}
int isPrime(int x){
return prime(x, sqrt(x));
}
int prime(int x, int i){
if(i==0){
return 0;
}
else if(mod(x,i)==1){
return 1;
}
else{
return prime(x, i-1);
}
}
int mod(int num, int div){
if(num<div) return num;
else return mod(num-div, div);
}
The algorithm is returning this:
Prime numbers between 0 and 31
0, 1, 2, 3, 4, 6, 8, 12, 14, 18, 20, 24, 30,
Program ended with exit code: 0
Your basic idea is fine. In Haskell you can use lists instead of iteration. Here's what you need to look into:
Install and play with ghci.
If you have no idea how to do anything in Haskell, visit Learn You a Haskell for Great Good http://learnyouahaskell.com/
List comprehensions. Lean what [n^2 | n <- [1..10]] means and play with similar lists.
Look up functions like sqrt on hoogle http://www.haskell.org/hoogle/
Because Haskell is statically typed you will need to convert some numerical types between Integer and Float. Look up Float -> Integer and Integer -> Float when you do. DON'T use unsafeCoerce - it's unsafe and will break things badly.
Use hoogle to look up [Bool] -> Bool. Why did I suggest that? How would [Bool] help, and how would you make one anyway? (Revise list comprehension again.)
Come back with more specific questions once you've found out more and had a go.
Always start your assignments early, especially if you've missed classes!
You were set this homework not because the department was stuck for a way of deciding whether 102659473841923461 is prime, but because they want you to learn some Haskell. Try not to try to solve the problem without doing the learning - it'll only make the next assignment even harder! (This is why I've resisted the temptation to translate the "pseudocode" in another answer into Haskell.)
(apparently, there's a new policy regarding homework, viz. "If you don't want a fully vetted, complete and testable answer, Stack Overflow is not the place to ask - by Tim Post", so here goes).
Basically, your code is almost correct (1 is not a prime), sans some syntax issues.
isprime x = prime x (floor $ sqrt $ fromIntegral x) where
prime x i | i==1 && x > 1 = 1
| x == i*div x i = 0
| otherwise = prime x (i-1)
-- mod x i = x - i*div x i
-- mod x i == 0 = x == i*div x i
fromIntegral is just some adaptor which lets us use an Integral value as an argument to sqrt which expects a Floating argument. Try using :i sqrt or :i Integral etc. at the GHCi prompt (also read some documentation google around).
But algorithmically there's place for improvement. First of all, it's much better to try out the divisors in the other direction, from 2 up to the number's sqrt, because any given number is more likely to have a smaller factor than a larger one. Second, after trying out 2, there's no need to try out any other even number as a possible divisor. This gives us
isprime x | x == 2 = 1
| x < 2 || even x = 0
| otherwise = go 3
where
r = floor $ sqrt $ fromIntegral x
go i | i > r = 1
| x == i*div x i = 0 -- really, | rem x i == 0 = 0
| otherwise = go (i+2)
This would normally be written down using Bools, and a higher-order function like and which captures the recursions and testing pattern (so it is not recursive anymore):
isprime x = if isPrime x then 1 else 0
isPrime x = x==2 || x>2 && odd x &&
and [rem x d /= 0 | d <- [3,5..floor $ sqrt $ fromIntegral x]]
There's some redundancy in there still: after we've tested by 3, there's no need to test by any of its multiples too (just like we did with 2 and evens). We really just need to test by prime factors:
isPrime x = x>1 && and
[rem x d /= 0 | d <- takeWhile (<= (floor $ sqrt $ fromIntegral x)) primes]
primes = filter isPrime [2..]
= 2 : filter isPrime ([3..] `minus` [4,6..])
= 2 : filter isPrime [3,5..]
= 2 : 3 : filter isPrime ([5,7..] `minus` [9,15..])
= 2 : 3 : 5 : filter isPrime (([7,9..]`minus`[9,15..])`minus`[25,35..])
...........
Here we see the emergence of the sieve of Eratosthenes, P = {3,5, ...} \ U {{p2, p2 + 2p, ...} | p in P} (w/out the 2).
see also:
http://en.wikipedia.org/wiki/Haskell_features#Prime_numbers
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
http://www.haskell.org/haskellwiki/Prime_numbers
I don't know Haskell, and I don't want to hand you the answer, but I can offer a method.
if you check all the numbers from 2 to sqrt(n), and none of them are factors of n, then n is prime.
So maybe a function call with the following pseudo code might work:
def isPrime(n):
return isPrimeHelper(n,sqrt(n))
def isPrimeHelper(n,counter):
if counter == 1 return True
if n % counter == 0 return False
else return isPrime(n,counter-1)