开发者

Finding the intercept of an x-axis - Haskell

I have defined the following function to determine where a line intercepts the x axis of a straight line graph. It should return (Float, Bool) where Float is the location the line crosses the x axis and Bool is True if it meets the x axis at > 0 and False if it does not.

x-intercept :: (Int, Int) -> (Float, Bool)
x-intercept (x,y)
  | x>0 = (x开发者_StackOverflow中文版, True)
  | otherwise = (x, False)

However, I am getting the following error:

Syntax error in declaration (unexpected ';', possibly due to bad layout)

Any ideas what I'm doing wrong?


- is illegal in function names in Haskell (as opposed to Lisp dialects). GHC 7.0.3 generates a better error message though:

Invalid type signature: x - intercept :: (Int, Int)
                                         -> (Float, Bool)
Should be of form <variable> :: <type>

Fix: rename your function to xIntercept. Then, you will face another problem: you use the variable x both as Int and as Float. This is illegal as well, you'll have to use fromIntegral to fix it.


As others have already answered your question, I would suggest a design change in the function definition.

x-intercept :: (Int, Int) -> Maybe Float

This way the function will return a Just float value in case the line intercept otherwise it will return Nothing


Haskell is not Lisp. You cannot have a hyphen in your expression-binding-name.


  • x-intercept is x - intercept
  • x is Int but you should return Float in tuple (eg: fromIntegral)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜