Reputation: 13
So I'm new to learning Haskell (started on Saturday) and I read a few chapters from online books and I wrote a list comprehension to find the diameter of a circle given its circumference.
ghci> let circle = [(a) | a <- [1..10], 9 / pi == a]
but it returns []
I was told this is because [1..10]
only counts whole integers and not all the real numbers between 1 and 10.
I tried ghci> let circle = [(a) | a <- [1..10], round (pi * a) == 9]
which returns [3.0]
but I was wondering if there was a way to get a more precise answer.
Thanks in advance.
Upvotes: 1
Views: 283
Reputation: 24166
Why don't you just find the diameter of a circle with a given circumference?
diameterOfCircleWithCircumference :: Floating a => a -> a
diameterOfCircleWithCircumference = (/ pi)
Then diameterOfCircleWithCircumference 9
is 2.8947...
Upvotes: 1
Reputation: 8492
Welcome to Haskell and StackOverflow!
let circle = [(a) | a <- [1..10], 9 / pi == a]
Considering all the real numbers between 1 and 10 is an uncountably infinite set (hat tip to Georg Cantor for that one) I'd be surprised, to say the least, if you managed to make a list comprehension over them. :)
Your reasoning about why this list is empty is correct -- 9/pi
will never equal a whole integer.
Other than that, there's no reason to use a list comprehension for this. You can do the same thing by simply dividing by pi:
let diam c = c / pi
Upvotes: 6
Reputation: 57630
This is not what list comprehensions are used for. To get a precise answer to 9 / pi
, just calculate 9 / pi
directly.
ghci> let diam = 9/pi
Upvotes: 3
Reputation: 6563
diameter c = c / pi
or as you get more advanced in Haskell:
diameter = (/ pi)
And then you can call:
Prelude> diameter 9
2.864788975654116
A list comprehension may be useful if you wanted the diameters of the circles with circumferences from 1 to 10, like so:
Prelude> [diameter x | x <- [1..10]]
[0.3183098861837907,0.6366197723675814,0.954929658551372,1.2732395447351628,1.5915494309189535,1.909859317102744,2.228169203286535,2.5464790894703255,2.864788975654116,3.183098861837907]
Upvotes: 1