Haskell filter function error - haskell

I want to list all integers that divide n. This is a homework question. So far I have done this.
divisors :: Int -> [Int]
divisors n | n < 1 = []
| otherwise = filter (\n -> n `mod` x == 0) [1..n]
where x = [1..n]
I know this is wrong, but I am not getting the right filter predicate. I don't know how the syntax is for doing this. and ofcourse I cannot use n mod n since that is just lists all elements 1 to n.

You want to check if mod n k == 0 for each k from 1 to n. The n is fixed (the argument of divisors) and the k varies, i.e. that is what should be the argument of the lambda expression
| otherwise = filter (\k -> n `mod` k == 0) [1 .. n]

I don't know what you are trying to do, but the type of mod is
mod :: Integral a => a -> a -> a
You call it with an Integral argument and a list of integral arguments.

Related

Prime Factorization in Haskell to return a list of tuples giving the number and the power

I have been trying to learn haskell by trying to do some simple problems.
The Problem
Currently, I am trying to implement a function primeFactorization :: Integer -> [(Integer, Integer)] such that the output is a list of tuples containing the prime factor and the power it is raise to in the number.
Example Output
> primeFactorization 120
[(2,3), (3,1), (5,1)] since 120 = 2^3 * 3^1 * 5^1
My (Partial) Solution
primeFactorization :: Integer -> [Integer]
primeFactorization n =
let
factors :: Integer -> [Integer]
factors n = [x | x <- [2..n-1], n `mod` x == 0]
isPrime :: Integer -> Bool
isPrime n
| n `elem` [0, 1] = False
| n == 2 = True
| n > 2 = null [ x | x <- [2..(ceiling . sqrt . fromIntegral) n], n `mod` x == 0]
| otherwise = False
in
filter isPrime $ (factors n)
This is a working implementation to get the prime factors of a number. However as seen it only outputs the prime factors. I am not sure on how to store the number of times in haskell. Also, considering it is un-idiomatic to iterate in haskell I don't know how I would implement the solution. In python, I would do:
def pf(number):
factors=[]
d=2
while(number>1):
while(number%d==0):
factors.append(d)
number=number/d
d+=1
return factors
So, the question: How to implement the powers of the prime factors?
NOTE:
I already saw: Prime factorization of a factorial however that does not answer my question.
This is NOT a homework problem, I am learning independently.
You can always replace imperative-language loops (as long as they don't meddle with any global state) with recursion. That may not be the most elegant approach, but in this case it seems perfectly appropriate to imitate your inner Python loop with a recursive function:
dividerPower :: Integer -> Integer -> Int
dividerPower n d
| n`rem`d == 0 = 1 + dividerPower (n`quot`d) d
| otherwise = 0
(This counts “backwards” compared to the Python loop. You could also make it tail-recursive with a helper function and count forwards over an accumulator variable, but that's more awkward and I don't think there's a memory/performance benefit that would justify it in this case.)
You can either use that together with your Haskell code (for each of the factors you've already found, check how often it occurs), or extend it so the whole thing works like the Python solution (which is actually a lot more efficient, because it avoids for every number checking whether it's prime). For that you just need to give back the final n in the result. Let's use a where block for handling the pattern matching, and also make the rem and:
dividePower :: Integer -> Integer -> (Integer, Int)
dividePower n d
| r == 0 = (nfin, p'+1)
| otherwise = (n, 0)
where (n', r) = n `quotRem` d
(nfin, p') = dividePower n' d
Then the equivalent to your Python code is
pf :: Integer -> Integer -> [(Integer, Int)]
pf = go 2
where go d n
| n>1 = (d, p) : go (d+1) n'
| otherwise = []
where (n', p) = dividePower n d
This actually gives you, like in Python, the list including also non-dividers (with power 0). To avoid that, change the list-building to
| n>1 = (if p>0 then ((d,p):) else id) $ go (d+1) n'

Couldn't match expected type `Bool' with actual type `[[Integer]]

I'm new to Haskell and have a question about types, it error out because it couldn't match expected type. I believe squarePrime is a bool, correct me if i'm wrong and it is complaining because it wants a int? Can someone explain, thanks in advance.
squarePrimes n = [n^2 | (n) <- [2..n-1], (all (\a -> mod n a /= 0) [2..n-1])]
multiOfFive a = mod a 5 == 0
fun n = [n | n <-[1..n], multiOfFive || squarePrimes n]
The 'squarePrimes n' function returns a list of Integers, as opposed to a Bool or a list of Bools. Looking at the list comprehension:
[n^2 | (n) <- [2..n-1], (all (\a -> mod n a /= 0) [2..n-1])]
This will produce a list of n^2, of n pulled from the range [2..n-1], for every n that satisfies the condition:
(all (\a -> mod n a /= 0) [2..n-1])
Then, in the list comprehension used in the definition of 'fun':
[n | n <-[1..n], multiOfFive || squarePrimes n]
A list is being constructed of each n in the range 1 to n, as long as the following condition is true:
multiOfFive || squarePrimes n
Haskell is expecting this to evaluate to a Bool. However, 'multiOfFive' is being called without any argument, and 'squarePrimes n' returns a list of Integers, as opposed to a Bool.
Without knowing exactly what the intention of 'fun n' is, I have altered the provided code a little bit to get a list comprehension that loads without error:
fun n = [n | n <- [1..n], (multiOfFive n) || (elem n (squarePrimes n))]
Now, it uses the 'elem' function to check whether a given 'n' is an element of the list 'squarePrimes n'.
I believe squarePrimes is a Bool, correct me if I'm wrong
GHCi will tell you:
λ> let squarePrimes n = [n^2 | (n) <- [2..n-1], (all (\a -> mod n a /= 0) [2..n-1])]
λ> :t squarePrimes
squarePrimes :: Integral a => a -> [a]
It is complaining because it wants an int? Can someone explain
Here Integral i => i is any integer type. That could for example be Int or Integer. This is because the integer literals 0, 1, 2 and the arithmetic operators you use aren't restricted to a specific integer type.
You're using squarePrimes n as a Bool.
You're also using multiOfFive as a Bool when its type is:
λ> let multiOfFive a = mod a 5 == 0
λ> :t multiOfFive
multiOfFive :: Integral a => a -> Bool
so a function that takes an integer type and returns a Bool.

Check if Int `mod` every element of a list == 0

I'm writing a (Literate) Haskell code that bruteforces the lcm (least common multiple) of a list of Ints.
I already thought about a strategy, but I'm not that good with Haskell syntax and don't know a lot of functions.
This is the function so far:
> bruteforceLCM :: [Int] -> Int -> Int
> bruteforceLCM xs n = if EVERYELEMENTOFTHELIST `mod` n == 0
> then n
> else (bruteforceLCM xs (n+1))
Where xs is the list of all Ints and n is the current Int that gets checked for being the lcm.
The first call would be bruteforceLCM xs 2, because n=0 would be not divisible and n=1 would always return true, these cases are solved with pattern matching earlier.
What would I have to replace "EVERYELEMENTOFTHELIST" with to achieve my goal?
Greeting, Joe
EDIT: Here is the whole code now, thanks to dfeuer!
> bruteforceKGV :: [Int] -> Int -> Int
> bruteforceKGV xs n = if all p xs then n else (bruteforceKGV xs (n+1))
> where p x = n `mod` x == 0
Can you write down a function f :: Int -> Bool that checks if an Int is 0 modulo n? I'll leave this first step to you.
So now you have a function f :: Int -> Bool and a list of Ints, and you want to see if f x is True for every x in the list. We ask Hoogle, and it tells us about all. You'll use f as the first argument of all to do what you want.
You're starting out with
bruteforceLCM :: [Int] -> Int -> Int
bruteforceLCM xs n = if EVERYELEMENTOFTHELIST `mod` n == 0
then n
else (bruteforceLCM xs (n+1))
When you say EVERYELEMENTOFTHELIST `mod` n == 0, what you really mean is "For each element, x, of xs, x `mod` n == 0".
Let's write a predicate expressing what that says about an element of the list:
p x = x `mod` n == 0
Now we can use all, which takes our predicate and tells us if it's true for all elements of the list.
But now we might want to clean things up a bit at a higher level. Because Haskell is lazy, we don't need to be so explicit about the recursion. We can do something like this instead:
bfLCM xs = fromJust $ find SOMETHING [2..]
Unfortunately, running this leads to a lot of infinite loops, because your math actually turns out to be a little bit wrong. Can you figure out where your mistake is?

Haskell Numeric Type Frustration

I'm having an issue with a simple Haskell program. It's supposed to factor a number n-1 into the form (2^r)s where n is a Carmichael number. This isn't really pertinent to my question, but it's what the following set of functions aims to do.
divides::Int->Int->Bool
divides x y = not $ y `mod` x == 0
carmichaeltwos::Int->Int
carmichaeltwos n
| not $ divides 2 n =0
| otherwise = (+ 1) $ carmichaeltwos (n/2)
carmichaelodd::Int->Int
carmichaelodd n
| not $ divides 2 n = n
| otherwise = carmichaelodd (n/2)
factorcarmichael::Int->(Int, Int)
factorcarmichael n = (r, s)
where
nminus = n-1
r = carmichaeltwos nminus
s = carmichaelodd nminus
When I try to load this into GHCi, Haskell spits up:
No instance for (Fractional Int)
arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Int)
In the first argument of `carmichaelodd', namely `(n / 2)'
In the expression: carmichaelodd (n / 2)
In an equation for `carmichaelodd':
carmichaelodd n
| not $ divides 2 n = n
| otherwise = carmichaelodd (n / 2)
I know that the function / has type (/)::(Fractional a)=>a->a->a, but I don't see how to fix my program to make this work nicely.
Also, I realize that I'm basically computing the same thing twice in the factorcarmichael function. I couldn't think of any easy way to factor the number in one pass and get the tuple I want as an answer.
To divide two Ints when you know, as in this case, that the dividend is divisible by the divisor, use the div or quot function, i.e., div n 2 or quot n 2. (div and quot differ only in their handling of negative operands when the "true" quotient isn't an integer.)
Also, why are you defining divides as not $ mod y x == 0? Unless you're using a nonstandard meaning of "divides," you should be using just mod y x == 0 — x divides y iff y modulo x is zero.
As for combining carmichaeltwos and carmichaelodd, try using the until function:
factorcarmichael n = until (\(_, s) -> not $ divides 2 s)
(\(r, s) -> (r+1, div s 2))
(0, n-1)

Haskell 'any' function - primality check

I'm trying to define an is_prime function in Haskell. Can anyone point out the issue with the use of the any function?
In addition, I know that the below code is naïve, but I am learning the language so starting with babysteps.
is_prime 0 = False
is_prime 1 = False
is_prime 2 = True
is_prime n = any [n `mod` k == 0 | k <- [2.. sqrt n]]
Type of any is (a -> Bool) -> [a] -> Bool, so it accepts a predicate and a collection. So you should rewrite your last case as for instance
is_prime n = not $ any (\k -> n `mod` k /= 0)
[2 .. ceiling $ sqrt $ fromIntegral n]
fromIntegral is necessary because sqrt's type is Floating a => a -> a while your n is an integer. Subsequently, without ceiling the second argument of any would be Floating t => [t]. This would break, as calling mod, whose type is Integral a => a -> a -> a, on non-integral types is illegal.
If you'd like to look for some other implementations, I can recommend for example this discussion.
The accepted answer is, to my mind, incorrect as the is_prime function actually returns False if n is a prime, and here's why.
any function data returns True as soon as it encounters such an element in data that function data is True.
\k -> mod n k /= 0 returns True if applied to a number that does not divide some constant n.
thus, any returns True if there is a number in the given list that does not divide the number n we want to check for primality and False if there is one.
so, is_prime returns True for any number that is divisible by any number in the list [2 .. ceiling $ sqrt $ fromIntegral n], for example, 4 which clearly is not a prime.
With that said, the correct solution should look like this:
is_prime n = not $ any (\k -> n `mod` k == 0) [2 .. ceiling $ sqrt $ fromIntegral n]
This is because a number n is prime if it's not a multiple of any number between 2 and sqrt n.

Resources