Home > Blockchain >  Can I get some idea with this haskell exercise?
Can I get some idea with this haskell exercise?

Time:10-02

I got this exercise, but I do not know how to start and solve it.

Point on one axis

  • Determine if a point represented by a coordinate lies on it
  • in the axis in the coordinate system!
  • Use pattern matching! Do not use equality testing or branching.
  • Also specify the type of function!
  • Each of the following test cases must give a True:
  • onAxis (0, 0)
  • onAxis (0, 100)
  • onAxis (50, 0)
  • onAxis (-12, 0)
  • not (onAxis (4, 5))

CodePudding user response:

Haskell's pattern matching is a powerful and useful feature. For example, you can have multiple formulas for your function and Haskell will choose the one where, e.g., the argument patterns match:

isZero :: Int -> Bool
isZero 0 = True
isZero _ = False

This simple little function should just tell me if my argument is equal to Zero. I do this without any comparison, just by pattern matching. 0 matches.. well, literally 0. But _ matches everything. The order matters here, the first formula to match is chosen.

So what about your points? They are represented as Tuples: (x, y). We can "look into" values with pattern matching:

isZeroPoint :: (Int, Int) -> Bool
isZeroPoint (0, 0) = True
isZeroPoint _      = False

OK, so how do we know if a (2 dimensional) point is on the X or Y axis? Look at the examples given, it should be quite obvious by now!

With this, you should be able to solve your exercise! Report back if you did it or still have questions ;)

PS: I'm not spelling out the complete solution, because I don't think it helps you if I do your homework for you.

PPS: I simply chose the concrete type Int for simplicity and because I don't know what else about Haskell types you have already learned. One could use a different number type (e.g., Integer) or something more general.

  • Related