Haskell Type errors - haskell

First day learning haskell, and coming from a python background I'm really having trouble debugging when it comes to type; Currently I'm working on a simple function to see if a number is a prime;
prime p = if p == 1 then False else if p == 2 then True else if maximum ([if p `mod` x == 0 then x else -1 | x<-[2..(floor(p**0.5))]]) > 0 then False else True
It works when I have a specific number instead of the generic P, but no matter what I try (and I've tried a lot, including just moving onto different problems) I always get some kind of error regarding type. For this current iteration, I'm getting the error
<interactive>:149:1: error:
* Ambiguous type variable `a0' arising from a use of `prime'
prevents the constraint `(RealFrac a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance RealFrac Double -- Defined in `GHC.Float'
instance RealFrac Float -- Defined in `GHC.Float'
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the expression: prime 2
In an equation for `it': it = prime 2
<interactive>:149:7: error:
* Ambiguous type variable `a0' arising from the literal `2'
prevents the constraint `(Num a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance Num Integer -- Defined in `GHC.Num'
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
...plus two others
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the first argument of `prime', namely `2'
In the expression: prime 2
In an equation for `it': it = prime 2
If someone could, as well as debugging this particular program, give me a heads up on how to think of haskell types, I'd be incredibly grateful. I've tried looking at learnyouahaskell but so far I've had no luck applying that.

In short: by using mod, floor, and (**) all at the same time, you restrict the type of p a lot, and Haskell fails to find a numerical type to call prime.
The main problem here is in the iterable of your list comprehension:
[2..(floor(p**0.5))]
Here you call p ** 0.5, but since (**) has type (**) :: Floating a => a -> a -> a, that thus means that p has to be an instance of a type that is an instance of the Floating typeclass, for example a Float. I guess you do not want that.
Your floor :: (RealFrac a, Integral b) => a -> b even makes it worse, since now p also has to be of a type that is an instance of the RealFrac typeclass.
On the other hand, you use mod :: Integral a => a -> a -> a, so it means that your p has to be Floating, as well as Integral, which are rather two disjunctive sets: although strictly speaking, we can define such a type, it is rather weird for a number to be both Integral and Floating at the same type. Float is for instance a Floating number, but not Integral, and Int is Integral, but not a Floating type.
We have to find a way to relax the constraints put on p. Since usually non-Integral numbers are no primes at all, we better thus aim to throw out floor and (**). The optimization to iterate up to the square root of p is however a good idea, but we will need to find other means to enforce that.
One way to do this is by using a takeWhile :: (a -> Bool) -> [a] -> [a] where we take elements, until the square of the numbers is greater than p, so we can rewrite the [2..(floor(p**0.5))] to:
takeWhile (\x -> x * x <= p) [2..]
We even can work only with odd elements and 2, by writing it as:
takeWhile (\x -> x * x <= p) (2:[3, 5..])
If we test this with a p that is for instance set to 99, we get:
Prelude> takeWhile (\x -> x * x <= 99) (2:[3, 5..])
[2,3,5,7,9]
If we plug that in, we relaxed the type:
prime p = if p == 1 then False else if p == 2 then True else if maximum ([if p `mod` x == 0 then x else -1 | x <- takeWhile (\x -> x * x <= p) (2:[3, 5..])]) > 0 then False else True
we actually relaxed it enough:
Prelude> :t prime
prime :: Integral a => a -> Bool
and we get:
Prelude> prime 23
True
But the code is very ugly and rather un-Haskell. First of all, you here use maximum as a trick to check if all elements satisfy a predicate. But it makes no sense to do that this way: from the moment one of the elements is dividable, we know that the number is not prime. So we can better use the all :: (a -> Bool) -> [a] -> Bool function. Furthermore conditions are usually checked by using pattern matching and guards, so we can write it like:
prime :: Integral a => a -> Bool
prime n | n < 2 = False
| otherwise = all ((/=) 0 . mod n) divisors
where divisors = takeWhile (\x -> x * x <= n) (2:[3, 5..])

Your code can be simplified as
prime p = if p == 1 then False else
if p == 2 then True else
if maximum ([if p `mod` x == 0 then x else -1 | x<-[2..(floor(p**0.5))]]) > 0
then False else True
=
prime p = if p == 1 then False else
if p == 2 then True else
not (maximum [if p `mod` x == 0 then x else -1 | x<-[2..floor(p**0.5)]] > 0 )
=
prime p = not ( p == 1 ) &&
( p == 2 ||
maximum [if p `mod` x == 0 then x else -1 | x<-[2..floor(p**0.5)]] <= 0 )
=
prime p = p /= 1 &&
( p == 2 ||
maximum [if p `mod` x == 0 then x else -1 | x<-[2..floor(p**0.5)]] == -1 )
=~
prime p = p == 2 || p > 2 && null [x | x <- [2..floor(p**0.5)], p `mod` x == 0]
(convince yourself in the validity of each transformation).
This still gives us a type error of course, because (**) :: Floating a => a -> a -> a and mod :: Integral a => a -> a -> a are conflicting. To counter that, just throw a fromIntegral in there:
isPrime :: Integral a => a -> Bool
isPrime p = p == 2 ||
p > 2 && null [x | x <- [2..floor(fromIntegral p**0.5)], p `mod` x == 0]
and it's working:
~> filter isPrime [1..100]
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]

Related

Function that tells if a number ir prime or not

``
I'm a Haskell newbie and I'm defining a function that given an Int n it tells if a number is prime or not by searching for an 2<=m<=sqrt(n) that mod n m ==0
if such m exists, then n is not prime, if not then n is prime.
I'm trying to define a list with numbers m between 2 and sqrt n, that mod n m ==0
My thought is that if the list is empty then n is prime, it not, n is not prime
`
isprime' :: Int -> Bool
isprime' n | l == [] = True
| otherwise = False
where
l = [x|x<-[2.. sqrt n], mod n x == 0]
`
But there seems to be a problem with sqrt n when I run my code and I can't understand it. can someone explain what I'm doing wrong/what to change for my code to run/ and why there's an error?
Running the code gives the following error
test.hs:9:28: error:
• No instance for (Floating Int) arising from a use of ‘sqrt’
• In the expression: sqrt n
In the expression: [2 .. sqrt n]
In a stmt of a list comprehension: x <- [2 .. sqrt n]
|
9 | l = [x|x<-[2.. sqrt n], mod n x == 0]
| ^^^^^^
You are correct in saying that the error is with sqrt, but the rest is pretty opaque to a new Haskell developer. Lets try by checking the type of sqrt to see if that helps.
Prelude> :t sqrt
sqrt :: Floating a => a -> a
Here I'm using ghci to interactively write code. :t asks for the type of the preceeding expression. The line sqrt :: Floating a => a -> a says sqrt takes in some floating point number a and returns something of the same type.
Similar to our error message we see this Floating thing. this thing is a typeclass but for the sake of solving this problem we'll save understanding those for later. In essence, haskell is trying to tell you that Int is not floating point number which is what sqrt expects. We can amend that by turning our Int into a Float with fromIntegral which is a really general function for turning number types into one another. (see Get sqrt from Int in Haskell)
isprime' :: Int -> Bool
isprime' n | l == [] = True
| otherwise = False
where
asFloat :: Float -- new! - tell fromIntegral we want a float
asFloat = fromIntegral n -- new! turn n into a Float
l = [x|x<-[2..sqrt asFloat], mod n x == 0]
This also errors! but it's a new one!
test.hs:10:48: error:
• Couldn't match expected type ‘Int’ with actual type ‘Float’
• In the second argument of ‘mod’, namely ‘x’
In the first argument of ‘(==)’, namely ‘mod n x’
In the expression: mod n x == 0
|
10 | l = [x|x<-[2..sqrt asFloat], mod n x == 0]
| ^
this is saying that x is suddenly a Float. When we changed to [2..sqrt asFloat] we now have made a list of Floats ([Float]). We need to change that back to [Int]. we can do that by calling floor on the result of the square root.
isprime' :: Int -> Bool
isprime' n | l == [] = True
| otherwise = False
where
asFloat :: Float
asFloat = fromIntegral n
l = [x|x<-[2..floor (sqrt asFloat)], mod n x == 0] -- new! I added floor here to change the result of sqrt from a `Float` into a `Int`
This now correctly compiles.

Haskell Beginner problems, list comprehension with single input

I am brand new to haskell and functional programming in general.
How can I create a function that finds all odd numbers less than 200 that are divisible by 3 and 7 using only list comprehension?
this is my code:
oddsDivisible3and7 :: Integer -> Integer -> Integer -> Integer -> [Integer]
oddsDivisible3and7 xs = [x | x <- [1..xs],x mod 3 == 0 && x mod 7 == 0,x < 200]
and the errors it is throwing:
• Couldn't match expected type ‘(Integer -> Integer -> Integer)
-> Integer -> Integer’
with actual type ‘Integer’
• The function ‘x’ is applied to two arguments,
but its type ‘Integer’ has none
In the first argument of ‘(==)’, namely ‘x mod 3’
In the first argument of ‘(&&)’, namely ‘x mod 3 == 0’
with another block for the mod 7
I'm not looking for a written function, I just need some guidance.
There are a few type error and a few sintax error, let me show:
oddsDivisible3and7 :: Integral a => a -> [a]
oddsDivisible3and7 n = [x | x <- [1..n],
x `mod` 3 == 0 && x `mod` 7 == 0 && x < 200 && x `mod` 2 /= 0]
first of all the type should be: Integral a => a -> [a]
Then, you want the divisible by 3, 7 and the odds (not divisible by 2), and all less than 200.
example:
oddsDivisible3and7 500
=> [21,63,105,147,189]

fractional type is in Haskell

I want to use rational number type instead of factional type in Haskell (or float/double type in C)
I get below result:
8/(3-8/3)=23.999...
8/(3-8/3)/=24
I know Data.Ratio. However, it support (+) (-) (*) (/) operation on Data.Ratio:
1%3+3%3 == 4 % 3
8/(3-8%3) == 24 % 1
I had checked in Racket:
(= (/ 8 (- 3 (/ 8 3))) 24)
#t
What's correct way to ensure 8/(3-8/3) == 24 in Haskell?
Use an explicit type somewhere in the chain. It will force the entire calculation to be performed with the corrrect type.
import Data.Ratio
main = do
print $ 8/(3-8/3) == 24
print $ 8/(3-8/3) == (24 :: Rational)
Prints
False
True
Data.Ratio.numerator and Data.Ratio.denominator return numerator an denominator of the ratio in reduced form so it is safe to compare denominator to 1 to check if ratio is an integer.
import Data.Ratio
eq :: (Num a, Eq a) => Ratio a -> a -> Bool
eq r i = d == 1 && n == i
where
n = numerator r
d = denominator r
main = print $ (8/(3-8%3)) `eq` 24

Haskell: pattern matching on Num types

Why can't Haskell perform pattern matching on Num types, without us specifying Eq as a type class?
For instance:
h :: Num a => a -> a
h 0 = -1
h x = x + 1
When compiling this function, ghci complains:
* Could not deduce (Eq a) arising from the literal `0'
from the context: Num a
bound by the type signature for:
h :: forall a. Num a => a -> a
at functions.hs:9:1-20
Possible fix:
add (Eq a) to the context of
the type signature for:
h :: forall a. Num a => a -> a
* In the pattern: 0
In an equation for `h': h 0 = - 1
|
10 | h 0 = -1
| ^
Changing the function definition as following compiles and runs perfectly:
h :: (Num a, Eq a) => a -> a
h 0 = -1
h x = x + 1
*Main> h 0
-1
*Main>
From the Haskell 2010 Report, the section entitled Informal Semantics of Pattern Matching:
Matching a numeric, character, or string literal pattern k against a value v succeeds if v == k
So when you use a literal (such as 0) as a pattern, its meaning depends upon == (a method of the Eq class).
For example, your function h
h 0 = -1
h x = x + 1
can be rewritten as
h x | x == 0 = -1
h x = x + 1
You are (implicitly) using the == method, therefore you need an Eq constraint.
There are two important observations here about how Haskell differs from a lot of other languages:
The notion of equality is not defined for all types. One cannot ask whether x == y unless the type of x and y has an Eq instance.
The set of numeric types is not fixed. A numeric literal can take on any type that has an instance of Num. You can define your own type and make it an instance of Num, and it doesn't necessarily have to also have an instance of Eq. So not all "numbers" can be compared for equality.
So it is insufficient for the context of your function h to be "a has to be a number." The context must be, more specifically, "a has to be a number with an equality test" to ensure that there is a way to check whether x is equal to 0 in order to perform the pattern match.

Custom Ord instance hangs on lists

import Data.Function (on)
import Data.List (sort)
data Monomial = Monomial
{ m_coeff :: Coefficient
, m_powers :: [(Variable, Power)]
}
deriving ()
instance Ord Monomial where
(>=) = on (>=) m_powers
instance Eq Monomial where
(==) = on (==) m_powers
That's an excerpt from my code, cut down to principal size. Let's try comparing:
*Main> (Monomial 1 [("x",2)]) > (Monomial (-1) [])
/* Computation hangs here */
*Main> (Monomial 1 [("x",2)]) < (Monomial (-1) [])
/* Computation hangs here */
On a side note, it's interesting that if I replace s/(>=)/(>)/g in instance declaration, it will not hang on the fist pair, but still will on the second:
*Main> (Monomial 1 [("x",2)]) > (Monomial (-1) [])
True
*Main> (Monomial 1 [("x",2)]) < (Monomial (-1) [])
/* Computation hangs here */
Although the standard states minimal declaration of Eq instance to be either$compare$ or $(>=)$.
What might be the problem here? (>=) on lists seems to work just fine.
Short answer:
You need to provide either (<=) or compare to have a complete definition for Ord, not (>=).
Longer explanation:
It is common for type classes in Haskell to have default implementations of some methods implemented in terms of other methods. You can then choose which ones you want to implement. For example, Eq looks like this:
class Eq a where
(==), (/=) :: a -> a -> Bool
x /= y = not (x == y)
x == y = not (x /= y)
Here, you must either implement (==) or (/=), otherwise trying to use either of them will cause an infinite loop. Which methods you need to provide is usually listed as the minimal complete definition in the documentation.
The minimal complete definition for Ord instances, as listed in the documentation, is either (<=) or compare. Since you've only provided (>=), you have not provided a complete definition, and therefore some of the methods will loop. You can fix it by e.g. changing your instance to provide compare instead.
instance Ord Monomial where
compare = compare `on` m_powers
Let's look at the default instance for Ord:
class (Eq a) => Ord a where
compare :: a -> a -> Ordering
(<), (<=), (>), (>=) :: a -> a -> Bool
max, min :: a -> a -> a
compare x y = if x == y then EQ
-- NB: must be '<=' not '<' to validate the
-- above claim about the minimal things that
-- can be defined for an instance of Ord:
else if x <= y then LT
else GT
x < y = case compare x y of { LT -> True; _ -> False }
x <= y = case compare x y of { GT -> False; _ -> True }
x > y = case compare x y of { GT -> True; _ -> False }
x >= y = case compare x y of { LT -> False; _ -> True }
-- These two default methods use '<=' rather than 'compare'
-- because the latter is often more expensive
max x y = if x <= y then y else x
min x y = if x <= y then x else y
So, if you supply >= and == as above, only, then you are in trouble, since:
> is defined in terms of compare
But
compare is defined in terms of <=
<= is defined in terms of compare
So you have an infinite loop!
A minimum definition must defined <= or compare, not '>=`.

Resources