I have to write a simple pi approximation and I did and it works fine, but in the task it says to write a function with the header "pi_approx :: Int -> Double".
My code:
pi_approx x = sqrt (pi2_approx(x))
pi2_approx x =
if x/= 1
then (6 /(x*x)) + (pi2_approx(x-1))
else (6/(1*1))
However my function works fine without "pi_approx :: Int -> Double", but when i try to use this declaration I always get the type error:
pi_approx.hs:10:14: error:
Couldn't match expected type Double' with actual type Int'
In the expression: (+) (6 / (x * x)) (pi2_approx (x - 1))
In the expression:
if x /= 1 then
(+) (6 / (x * x)) (pi2_approx (x - 1))
else
(6 / (1 * 1))
In an equation for `pi2_approx':
pi2_approx x
= if x /= 1 then
(+) (6 / (x * x)) (pi2_approx (x - 1))
else
(6 / (1 * 1))
|
10 | then (+) (6 /(x*x)) (pi2_approx(x-1))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I tried to use fromIntegral in various ways and if I run the function without declaration I checked the type of the solution, which is: "(Floating a, Eq a) => a"
As I understand Double should be an instance of Floating so I don´t understand why it wont compile.
I am very new at haskell and it seems I don´t understand the core concept of data types and constraints. I can´t seem to find any simple and good documentation/explanation on the topic though. Maybe someone here can help me understand based on this example :)
because x is an Int, hence x * x is also an Int, and you can not use an Int for (/) :: Floating a => a -> a -> a.
You need to convert this to a Double, for example with fromIntegral :: (Integral a, Num b) => a -> b:
pi2_approx :: Int -> Double
pi2_approx 1 = 6
pi2_approx x = 6 / fromIntegral (x*x) + pi2_approx (x-1)
For a large number of iterations, it gives a result close to π2:
Prelude> sqrt (pi2_approx 10000)
3.1414971639472147
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
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]
This Haskell program prints "1.0" How can I get it to print "1"?
fact 0 = 1
fact x = x * fact (x-1)
place m n = (fact m) / (fact n) * (fact (m-n))
main = do
print (place 0 0)
By using the / operation, you are asking haskell to use a fractional data type. You probably don't want that in this case. It is preferable to use an integral type such as Int or Integer. So I suggest to do the following:
1. Add a type declaration for the fact function, something like fact :: Integer -> Integer
2. Use quot instead of /.
So your code should look like this:
fact :: Integer -> Integer
fact 0 = 1
fact x = x * fact (x-1)
place :: Integer -> Integer -> Integer
place m n = (fact m) `quot` (fact n) * (fact (m-n))
main = do
print (place 0 0)
Also, as #leftaroundabout pointed out, you probably want to use a better algorithm for computing those binomial numbers.
You could just use round:
print (round $ place 0 0)
This changes the formatting to the one you want. redneb's answer is, however, the right approach.
The Following code:
unSum :: Float -> Float
unSum x = (y + y`mod`2 + 2) / 2
where
y = x*(x+1) / 2
gives me this error when I try to load it into WinHugs 98:
Hugs> :load "D:\\kram\\unSumme2.hs"
ERROR file:.\unSumme2.hs:2 - Instance of Integral Float required for definition of unSumme2
What's the essence of this and how am I to do it? Anyway, I dont now if it serves my porpuse, I want to calculate the sum of the uneven numbers until x without recursivity.
It's because you're using mod. The definition of mod, from the Standard Prelude:
class (Real a, Enum a) => Integral a where
[...]
div, mod :: a -> a -> a
[...]
n `mod` d = r where (q,r) = divMod n d
In other words, it expects a to be of the numeric typeclass Integral, which includes only whole numbers.
If you want to stick with Floats, try using mod', from Data.Fixed, per this answer.
Alternatively, if you just want to do integer division, you could change your function's signature to
unSum :: Int -> Int
or similar.