variable not in scope - tail recursive sum - Haskell - haskell

I am stuck with the variable not in scope: m error.
This is supposed to be a code to sum n numbers in a tail recursion way.
zum :: Integer-> Integer
zum n = add_sum m n where
add_sum :: Integer-> Integer-> Integer
add_sum m n
| n == 0 = m
| otherwise = add_sum (m+n) (n-1)

In the second line of your code
zum n = add_sum m n where
'm' is not defined. Perhaps it was intended that instead of an 'm', there needs to be 0 there.

perhaps cleaner this way?
sum n = go 0 n
where go m 0 = m
go m n = go (m+n) (n-1)
> sum 4
10

Related

Convert a list of position,value tuples into a single list

I am writing some code to work with arbitrary radix numbers in haskell. They will be stored as lists of integers representing the digits.
I almost managed to get it working, but I have run into the problem of converting a list of tuples [(a_1,b_1),...,(a_n,b_n)] into a single list which is defined as follows:
for all i, L(a_i) = b_i.
if there is no i such that a_i = k, a(k)=0
In other words, this is a list of (position,value) pairs for values in an array. If a position does not have a corresponding value, it should be set to zero.
I have read this (https://wiki.haskell.org/How_to_work_on_lists) but I don't think any of these methods are suitable for this task.
baseN :: Integer -> Integer -> [Integer]
baseN n b = convert_digits (baseN_digits n b)
chunk :: (Integer, Integer) -> [Integer]
chunk (e,m) = m : (take (fromIntegral e) (repeat 0))
-- This is broken because the exponents don't count for each other's zeroes
convert_digits :: [(Integer,Integer)] -> [Integer]
convert_digits ((e,m):rest) = m : (take (fromIntegral (e)) (repeat 0))
convert_digits [] = []
-- Converts n to base b array form, where a tuple represents (exponent,digit).
-- This works, except it ignores digits which are zero. thus, I converted it to return (exponent, digit) pairs.
baseN_digits :: Integer -> Integer -> [(Integer,Integer)]
baseN_digits n b | n <= 0 = [] -- we're done.
| b <= 0 = [] -- garbage input.
| True = (e,m) : (baseN_digits (n-((b^e)*m)) b)
where e = (greedy n b 0) -- Exponent of highest digit
m = (get_coef n b e 1) -- the highest digit
-- Returns the exponent of the highest digit.
greedy :: Integer -> Integer -> Integer -> Integer
greedy n b e | n-(b^e) < 0 = (e-1) -- We have overshot so decrement.
| n-(b^e) == 0 = e -- We nailed it. No need to decrement.
| n-(b^e) > 0 = (greedy n b (e+1)) -- Not there yet.
-- Finds the multiplicity of the highest digit
get_coef :: Integer -> Integer -> Integer -> Integer -> Integer
get_coef n b e m | n - ((b^e)*m) < 0 = (m-1) -- We overshot so decrement.
| n - ((b^e)*m) == 0 = m -- Nailed it, no need to decrement.
| n - ((b^e)*m) > 0 = get_coef n b e (m+1) -- Not there yet.
You can call "baseN_digits n base" and it will give you the corresponding array of tuples which needs to be converted to the correct output
Here's something I threw together.
f = snd . foldr (\(e,n) (i,l') -> ( e , (n : replicate (e-i-1) 0) ++ l')) (-1,[])
f . map (fromIntegral *** fromIntegral) $ baseN_digits 50301020 10 = [5,0,3,0,1,0,2,0]
I think I understood your requirements (?)
EDIT:
Perhaps more naturally,
f xs = foldr (\(e,n) fl' i -> (replicate (i-e) 0) ++ (n : fl' (e-1))) (\i -> replicate (i+1) 0) xs 0

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

Stuck in recursion in rangeProduct function

I am a beginner in Haskell and I am stuck in a simple recursion function.
I am trying to define a function rangeProduct which when given natural numbers m and n returns the product
m*(m+1)...(n-1)*n
The function should return 0 when n is smaller than m.
What I've tried:
rangeProduct :: Int -> Int -> Int
rangeProduct m n
| m > n = 0
| otherwise = m * n * rangeProduct (m+1)(n-1)
But this is wrong because in the otherwise guard, when m gets bigger and n smaller, at some point m will get bigger than n and it will get 0 causing all what it has done so far to get multiplied by zero, resulting in 0 everytime I run the function.
I know the answer is simple but I am stuck. Can anyone help? Thanks!
Why bother incrementing and decrementing at the same time? Just go in one direction:
rangeProduct m n
| m > n = 0
| m == n = n
| otherwise = m * rangeProduct (m + 1) n
Although you could easily define this without recursion as
rangeProduct :: Integer -> Integer -> Integer
rangeProduct m n
| m > n = 0
| otherwise = product [m..n]

Check whether an integer (or all elements of a list of integers) be prime

I'm doing a simple Haskell function using recursion. At the moment, this seems to work but, if I enter 2, it actually comes up as false, which is irritating. I don't think the code is as good as it could be, so, if you have any advice there, that'd be cool too!
I'm pretty new to this language!
EDIT: Ok, so I understand what a prime number is.
For example, I want to be able to check 2, 3, 5, 7, etc and have isPrime return true. And of course if I run the function using 1, 4, 6, 8 etc then it will return false.
So, my thinking is that in pseudo code I would need to do as follows:
num = 2 -> return true
num > 2 && num = even -> return false
After that, I'm struggling to write it down in any working code so the code below is my work in process, but I really suck with Haskell so I'm going nowhere at the minute.
module Recursion where
isPrime :: Int -> Bool
isPrime x = if x > 2 then ((x `mod` (x-1)) /= 0) && not (isPrime (x-1)) else False
Ok,
let's do this step by step:
In math a (natural) number n is prime if it has exactly 2 divisors: 1 and itself (mind 1 is not a prime).
So let's first get all of the divisors of a number:
divisors :: Integer -> [Integer]
divisors n = [ d | d <- [1..n], n `mod` d == 0 ]
then get the count of them:
divisorCount :: Integer -> Int
divisorCount = length . divisors
and voila we have the most naive implementation using just the definition:
isPrime :: Integer -> Bool
isPrime n = divisorCount n == 2
now of course there can be quite some impprovements:
instead check that there is no divisor > 1 and < n
you don't have to check all divisors up to n-1, it's enough to check to the squareroot of n
...
Ok just to give a bit more performant version and make #Jubobs happy ;) here is an alternative:
isPrime :: Integer -> Bool
isPrime n
| n <= 1 = False
| otherwise = not . any divides $ [2..sqrtN]
where divides d = n `mod` d == 0
sqrtN = floor . sqrt $ fromIntegral n
This one will check that there is no divisor between 2 and the squareroot of the number
complete code:
using quickcheck to make sure the two definitions are ok:
module Prime where
import Test.QuickCheck
divisors :: Integer -> [Integer]
divisors n = [ d | d <- [1..n], n `mod` d == 0 ]
divisorCount :: Integer -> Int
divisorCount = length . divisors
isPrime :: Integer -> Bool
isPrime n
| n <= 1 = False
| otherwise = not . any divides $ [2..sqrtN]
where divides d = n `mod` d == 0
sqrtN = floor . sqrt $ fromIntegral n
isPrime' :: Integer -> Bool
isPrime' n = divisorCount n == 2
main :: IO()
main = quickCheck (\n -> isPrime' n == isPrime n)
!!warning!!
I just saw (had something in the back of my mind), that the way I did sqrtN is not the best way to do it - sorry for that. I think for the examples with small numbers here it will be no problem, but maybe you really want to use something like this (right from the link):
(^!) :: Num a => a -> Int -> a
(^!) x n = x^n
squareRoot :: Integer -> Integer
squareRoot 0 = 0
squareRoot 1 = 1
squareRoot n =
let twopows = iterate (^!2) 2
(lowerRoot, lowerN) =
last $ takeWhile ((n>=) . snd) $ zip (1:twopows) twopows
newtonStep x = div (x + div n x) 2
iters = iterate newtonStep (squareRoot (div n lowerN) * lowerRoot)
isRoot r = r^!2 <= n && n < (r+1)^!2
in head $ dropWhile (not . isRoot) iters
but this seems a bit heavy for the question on hand so I just remark it here.
Here are two facts about prime numbers.
The first prime number is 2.
An integer larger than 2 is prime iff it's not divisible by any prime number up to its square root.
This knowledge should naturally lead you to something like the following approach:
-- primes : the infinite list of prime numbers
primes :: [Integer]
primes = 2 : filter isPrime [3,5..]
-- isPrime n : is positive integer 'n' a prime number?
isPrime :: Integer -> Bool
isPrime n
| n < 2 = False
| otherwise = all (\p -> n `mod` p /= 0) (primesPrefix n)
where primesPrefix n = takeWhile (\p -> p * p <= n) primes
As a bonus, here is a function to test whether all items of a list of integers be prime numbers.
-- arePrimes ns : are all integers in list 'ns' prime numbers?
arePrimes :: [Integer] -> Bool
arePrimes = all isPrime
Some examples in ghci:
ghci> isPrime 3
True
ghci> isPrime 99
False
ghci> arePrimes [2,3,7]
True
ghci> arePrimes [2,3,4,7]
False
You can get a recursive formulation from the "2 divisors" variant by step-wise refinement:
isPrime n
= 2 == length [ d | d <- [1..n], rem n d == 0 ]
= n > 1 && null [ d | d <- [2..n-1], rem n d == 0 ]
= n > 1 && and [ rem n d > 0 | d <- takeWhile ((<= n).(^2)) [2..] ]
= n > 1 && g 2
where
g d = d^2 > n || (rem n d > 0 && g (d+1))
= n == 2 || (n > 2 && rem n 2 > 0 && g 3)
where
g d = d^2 > n || (rem n d > 0 && g (d+2))
And that's your recursive function. Convince yourself of each step's validity.
Of course after we've checked the division by 2, there's no need to try dividing by 4,6,8, etc.; that's the reason for the last transformation, to check by odds only. But really we need to check the divisibility by primes only.

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

Resources