Parse error on guards - haskell

factorial :: Int -> Int
factorial 0 = 1
factorial n
| n < 0 == error "Cant call a nagative number"
| otherwise = n * factorial (n-1)
Can anybody explain why I am getting this error?
haskell.hs:77:2: parse error on input ‘|’

you need to use = not == in a function definition:
factorial :: Int -> Int
factorial 0 = 1
factorial n
| n < 0 = error "Cant call a nagative number"
| otherwise = n * factorial (n-1)
= is a syntactic atom used for defining things;
== is a function/operator used for comparing values.

Related

Haskell input with txt file

I am working on a program to get the closest prime number by the exponent of 2, this is between an interval.
module Main where
import Data.Char
import System.IO
import Control.Monad (liftM)
data PGetal = G Bool | P Int
instance Show PGetal where
show (P n) = show n
show (G False) = "GEEN PRIEMGETAL GEVONDEN"
mPriem::(Int, Int) -> PGetal
mPriem (x,y) | (x > y) = G False
| (x > 1000000) = G False
| (y > 1000000) = G False
| (null (getAllPriem(x,y))) = G False
| otherwise = P (kleinsteVerschilF(getAllPriem(x,y),1000000,1))
kleinsteVerschilF:: ([Int], Int , Int) -> Int
kleinsteVerschilF ([],_, priemGetal) = priemGetal
kleinsteVerschilF (priem1:priemcss, kleinsteVerschil,priemGetal)=
if(kleinsteVerschil <= kleinsteVerschilMetLijst (priem1,(getMachtenVanTwee(0)),1000000))then kleinsteVerschilF(priemcss, kleinsteVerschil,priemGetal)
else kleinsteVerschilF (priemcss,kleinsteVerschilMetLijst(priem1,(getMachtenVanTwee(0)),1000000), priem1)
kleinsteVerschilMetLijst :: (Int,[Int],Int) -> Int
kleinsteVerschilMetLijst ( _,[],kleinsteVerschil) = kleinsteVerschil
kleinsteVerschilMetLijst (x,tweeMachten1:tweeMachtencss,kleinsteverschil)=
if((abs(x-tweeMachten1)) < kleinsteverschil)
then kleinsteVerschilMetLijst(x,tweeMachtencss, (abs(x-tweeMachten1)))
else kleinsteVerschilMetLijst(x,tweeMachtencss, kleinsteverschil)
getAllPriem :: (Int, Int) ->[Int]
getAllPriem (x,y) = filter isPriem [x..y]
getMachtenVanTwee ::(Int) -> [Int]
getMachtenVanTwee (macht)
|(functieMachtTwee(macht)< 1000000) = (functieMachtTwee(macht)) : (getMachtenVanTwee ((macht+1)))
| otherwise = []
functieMachtTwee:: (Int) -> Int
functieMachtTwee (x) = 2^x
isPriem n = (aantalDelers n)==2
aantalDelers n = telAantalDelersVanaf n 1
telAantalDelersVanaf n kandidaatDeler
| n == kandidaatDeler = 1
| mod n kandidaatDeler == 0
= 1 + telAantalDelersVanaf n (kandidaatDeler+1)
| otherwise
= telAantalDelersVanaf n (kandidaatDeler+1)
aantalDelers2 getal = telDelers getal 1 0
where telDelers n kandidaat teller
| n == kandidaat = 1+teller
| mod n kandidaat == 0
= telDelers n (kandidaat+1) (teller+1)
| otherwise
= telDelers n (kandidaat+1) teller
transform :: [String] -> [PGetal]
transform [] = []
transform (cs:css) =
let (a : b: _ ) = words cs
in (mPriem ((read(a)),(read(b))): transform css)
main :: IO ()
main = do
n <- read `liftM` getLine :: IO Int
lss <- lines `liftM` getContents
let cases = take n lss
let vs = (transform (lss))
putStr $ unlines $ map show vs
When I use the mPriem function, it works fine.
But it needs to work with an input txt file, so I made a .exe file with the ghc command. I also added this .txt file in the folder.
10
1 1
1 3
1 100
200 250
14 16
5 10
20 31
16 50
100 120
5200 7341
When I use in command line this command, it does nothing. There is no output. I can't CTRL+C to stop the program, so I think it crashes. But I don't know what's wrong.
type invoer.txt | programma.exe
Your program works, but is not that efficient and personally I find it not that elegant (sorry :S) because you introduce a lot of "noise". As a result it takes a lot of time before output is written.
If I understand the problem statement correctly, each line (except the first), contains two integers, and you need to count the amount of prime numbers between these two numbers (bounds inclusive?)
First of all, you can do this more elegantly by defining a function: cPrime :: Int -> Int -> Int that takes as input the two numbers and returns the amount of prime numbers:
cPrime :: Int -> Int -> Int
cPrime a b = count $ filter isPrime [a .. b]
You can improve performance by improving your prime checking algorithm. First of all, you do not need to check whether 1 is a divisor, since 1 is always a divisor. Furthermore, you can prove mathematically that there is no divisor greater than sqrt(n) (except for n) that divides n; unless there is another divider that is smaller than sqrt(n). So that means that you can simply enumerate all numbers between 2 and sqrt n and from the moment one of these is a divisor, you can stop: you have proven the number is not prime:
isPrime :: Int -> Bool
isPrime 1 = False
isPrime 2 = True
isPrime n = all ((0 /=) . mod n) (2:[3,5..m])
where m = floor $ sqrt $ fromIntegral n
Now I'm not sure what you aim to do with kleinsteVerschilF.

haskell case that calls a function

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

Haskell Refresh a variables value

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

How can I write these functions to be independent of choice of type: Int vs Integer

I'm working through Project Euler, and a lot of problems involve similar functions, for example calculating lists of primes. I know calculations with Integer are slower than Int so I'd like to write the functions to work with both, depending on the size of the numbers I'm working with.
module Primes
(
isPrime
,prime
,allPrimes
)
where
import Data.List
isPrime :: Int -> Bool
isPrime n
| n == 0 = False
| n == 1 = False
| n < 0 = isPrime (-n)
| n < 4 = True
| n `mod` 2 == 0 = False
| n `mod` 3 == 0 = False
| any ( (==0) . mod n ) [5..h] = False
| otherwise = True
where
h = ( ceiling . sqrt . fromIntegral ) n
allPrimes :: [Int]
allPrimes = [ x | x<- [2..], isPrime x ]
prime :: Int -> Int
prime n = allPrimes !! (n-1)
I know this code isn't generally as optimal as it could be. I'm just interested in how to make the integer types more generic.
Try Integral it should allow support for both Int and Integer
A more general solution to this kind of problem, you could try getting your code to compile without the explicit type declarations. Haskell will assume the most general type possible and you can find out what it was by, for example, loading your file on GHCi and doing a :t myFunctionName

Function guard syntax in Haskell

fib::Int->Int
fib n
n==0 = 1
n>1 = error "Invalid Number"
this function gives me a error
Syntax error in declaration (unexpected symbol "==")
im not sure whats wrong with the function when compare to the reading material it looks the same
You're missing some of the syntax:
fib :: Int -> Int
fib n
| n == 0 = 1
| n > 1 = error "Invalid Number"
This can also be written without the first newline:
fib :: Int -> Int
fib n | n == 0 = 1
| n > 1 = error "Invalid Number"
This function is more naturally expressed with pattern matching:
fib :: Int -> Int
fib 0 = 1
fib n | n > 1 = error "Invalid number"
and you might be interested in the catalogue of fibonaccis.

Resources