3

I'm having some issues with the following exercise:

I'm supposed to write a function that thats 3 numbers, x y n, being x and y the bottom and upper bounds of a list comprehension (respectively) and n being the number of partitions that comprehension will have.

E.g:

λ> partition 10 20 4
[10.0, 12.5, 15.0, 17.5, 20.0]

What I have done is the following:

partition :: Double -> Double -> Double -> [Double]
partition x y n = [a+b | b = (y-x) / n ,  a -> [x,b..y]]

I don't understand why i can't define the value of the b variable inside the comprehension, since when i try to run it i get the following error message:

parse error on input `='

NOTE: This is supposed to be a beginners exercise and this should have a simple resolution

AJF
  • 11,767
  • 2
  • 37
  • 64
eXistanCe
  • 735
  • 1
  • 9
  • 25

2 Answers2

9

You just need to use the let keyword:

partition x y n = [a+b | let b = (y-x)/n ,  a <- [x,x+b..y]]

Then you can use b as desired:

λ partition 10 20 4
[12.5,15.0,17.5,20.0,22.5]
rampion
  • 87,131
  • 49
  • 199
  • 315
  • The results differ. [Related](http://stackoverflow.com/questions/7290438/haskell-ranges-and-floats). – effectfully Jul 24 '15 at 17:49
  • Oh i didn't know i could use let inside a comprehension, thank you. But that way the list goes up to y+b ( 22.5) instead of going just to 20.0, how can i fix it? – eXistanCe Jul 24 '15 at 20:20
  • 2
    @user3237465 I don't really think that's related. The bug here is using `a+b` instead of just `a`, not anything to do with Haskell's funny enumeration rules. – Daniel Wagner Jul 24 '15 at 20:22
  • @Daniel Wagner, yep, I didn't look at the first number and the length of the list. Anyway, it's "not safe" to use enumerations for floats like this. – effectfully Jul 24 '15 at 20:47
3

What variables? Everything is immutable :)

What you want is a let expression:

partition x y n = [let b = (y-x)/n in a+b | a <- [x,b..y]]

Also note the direction of the arrow: it comes from the list expression to a, not the other way around.

It looks more natural to move the common sub-expression away from the comprehension:

partition x y n = let b = (y-x)/n in [a+b | a <- [x,b..y]]
9000
  • 39,899
  • 9
  • 66
  • 104