Reputation: 677
I'm trying to define a function in Haskell that takes an integer argument c and returns the list of all points on the cartesian plane of the form (x/c,y/c)
where x
and y
are integers.
x/c
is between -2 and 1 and y/r
is between -1 and 1
This is what I've gotten so far which I'm almost sure is right but I'm getting a parse error on input =
when I run it particularly at this line: cart xs ys c = [(y/c,x/c) | x <- xs, y <- ys]
plane :: Int -> [a]
plane c = cart [-1*c .. 1*c] [-2*c .. 1*c] c
cart xs ys c = [(y/c,x/c) | x <- xs, y <- ys]
A sample output would be: plane 1
would generate:
[(-2.0, -1.0), (-1.0, -1.0), ( 0.0, -1.0), ( 1.0, -1.0),
(-2.0, 0.0), (-1.0, 0.0), ( 0.0, 0.0), ( 1.0, 0.0),
(-2.0, 1.0), (-1.0, 1.0), ( 0.0, 1.0), ( 1.0, 1.0)]
Anyone have any idea how I can fix this! Thanks
Upvotes: 2
Views: 293
Reputation: 5305
This is how I'd do it. fromintegral
is a type 'glue' function that converts any value in the Integral
type class to any other type in the Num
typeclass. The result type has to be in RealFrac
(like Double
or Rational
) to use the /
operator.
plane :: (Integral a, RealFrac b) => a -> [(b,b)]
plane d = [(fI y / fI d,fI x / fI d) | x <- [-2*d..d], y <- [-d..d]]
where fI = fromIntegral
Upvotes: 1
Reputation: 28539
you are missing the where
, other than that it looks like you have some type errors.
[a]
is too general/
only works on fractional types. so
plane :: Int -> [(Int,Int)]
plane c = cart [-1*c .. 1*c] [-2*c .. 1*c] c where
cart xs ys c = [(y `div` c,x `div` c) | x <- xs, y <- ys]
might be what you want. Smallest change from what you have that more or less works.
Upvotes: 4