Function guard syntax in Haskell - 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.

Related

Haskell Says My Guard Has A Parse Error

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)

Parse error on guards

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.

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

Partial memoization in Haskell

I'm trying to find a good way to memoize a function for only part of its domain (non-negative integers) in Haskell, using Data.MemoCombinators.
import Data.MemoCombinators
--approach 1
partFib n | n < 0 = undefined
| otherwise = integral fib n where
fib 0 = 1
fib 1 = 1
fib k = partFib (k-1) + partFib (k-2)
--approach 2
partFib2 n | n < 0 = undefined
| otherwise = fib n
fib = integral fib'
where
fib' 0 = 1
fib' 1 = 1
fib' n = partFib2 (n-1) + partFib2 (n-2)
Approach 1 is how I would like to do it, however, it doesn't seem to work. I assume this is because the fib function is "recreated" every time partFib is called, throwing away the memoization. fib doesn't depend on the input of partFib, so you would assume that the compiler could hoist it, but apparently GHC doesn't work that way.
Approach 2 is how I end up doing it. Eerk, a lot of ugly wiring.
Does anybody know of a better way to do this?
Not quite sure what's "ugly" to your eye, but you can have proper memoization while using only a single top-level identifier by lifting the memoization operation out of the function of n.
partFib3 = \n -> if n < 0 then undefined else fib' n
where fib 0 = 1
fib 1 = 1
fib k = partFib3 (k-1) + partFib3 (k-2)
fib' = integral fib
Hmm what about separating things a bit:
fib 0 = 0
fib 1 = 1
fib x = doFib (x-1) + doFib (x-2)
memFib = Memo.integral fib
doFib n | n < 0 = fib n
| otherwise memFib n
Now you need to use doFib.
There is a combinator in the library for this purpose:
switch :: (a -> Bool) -> Memo a -> Memo a -> Memo a
switch p a b uses the memo table a whenever p gives true and the memo table b whenever p gives false.
Recall that id is technically a memoizer (which does not memoize :-), so you can do:
partFib = Memo.switch (< 0) id Memo.integral fib'
where
...

How to check that I'm dealing with a list in Haskell?

I'm learning Haskell, and I'm trying to add preconditions to a (trivial, as an exercise) element_at function (code below). I've created a "helper" elem_at_r because otherwise, len x fails at some point (when x is a 'literal' rather than a list? - I still have trouble parsing ghci's error messages). elem_at now has all the error checking, and elem_at_r does the work. In elem_at, I'd like to add a check that x is indeed a list (and not a 'literal'). How can I do that?
len x = sum [ 1 | a <- x]
elem_at_r x n | n == 0 = head x
| 0 < n = elem_at_r (tail x) (n-1)
elem_at x n | x == [] = error "Need non-empty list"
| len x <= n = error "n too large " ++ show (len x)
| n < 0 = error "Need positive n"
| otherwise = elem_at_r x n
Thanks!
Frank
Due to Haskell's type system, elem_at can only take a list as its first argument (x); if you try to pass a non-list, GHC will detect this and give an error at compile time (or interpretation time in GHCi). I don't know why len would "fail"; could you post the error message that GHCi gives you?
It looks like you were getting errors because of the "x == []" line. The code below pattern matches for that condition and adds a few signatures. Otherwise it is the same. Hope it helps.
len x = sum [ 1 | a <- x]
elem_at_r :: [a] -> Int -> a
elem_at_r x n | n == 0 = head x
| 0 < n = elem_at_r (tail x) (n-1)
elem_at :: [a] -> Int -> a
elem_at [] _ = error "Need non-empty list"
elem_at x n | len x <= n = error ("n too large " ++ show (len x))
| n < 0 = error "Need positive n"
| otherwise = elem_at_r x n
You could also make your helper functions part of this function using a where clause:
elem_at :: [a] -> Int -> a
elem_at [] _ = error "Need non-empty list"
elem_at x n | len x <= n = error ("n too large " ++ show (len x))
| n < 0 = error "Need positive n"
| otherwise = elem_at_r x n
where
len :: [a] -> Int
len x = sum [ 1 | a <- x]
elem_at_r :: [a] -> Int -> a
elem_at_r x n | n == 0 = head x
| 0 < n = elem_at_r (tail x) (n-1)

Resources