2016-03-17 49 views
0

我是Haskell的新手。我从我的任务中得到了这个问题。它要求我做出此代码的工作:如何仅使用有效输入计算三角形的面积?

area_of_triangle :: Float 
       -> Float 
       -> Float 
       -> Maybe Float 

我知道如何做到这一点没有Maybe;它就像:

area_of_triangle :: Float -> Float -> Float -> Float 
area_of_triangle a b c = sqrt(s*(s-a)*(s-b)*(s-c)) 
    where 
    s = (a+b+c)/2 

我猜的要求是,如果area_of_triangle=0.0,返回Nothing(因为这样的三角形不存在)。但我不知道如何写这个。

+3

你可以使用一个'if'表达弄清楚,如果结果是'0',如果是,回'Nothing',否则返回'只是'。 –

+4

这不完全正确!并非所有的'a'' b'和'c'都会产生一个有效的三角形。例如,'area_of_triangle 100000000 1 1'。 – hao

+0

谢谢@会,休厄尔评论,我想通了,是这样的: area_of_triangle ::浮动 - >浮动 - >浮动 - >也许浮法 area_of_triangle ABC =如果area_answer/= 0.0 然后就area_answer 别的没什么 哪里 area_answer = sqrt(s *(sa)*(sb)*(sc)) 其中 s =(a + b + c)/ 2 如果我输入一个有效的“a” 'B','C'。但是,如果我为'a','b','c'输入无效的数字,则返回'Just NaN'。 现在我希望它可以返回'Just(Float)'或'Nothing',而不是'Just(Float)'或'Just NaN'。 –

回答

5

如果每对长度之和大于另一长度,则三条长度只能形成一个三角形。如果不是这样,请返回Nothing。否则,您可以返回Just a,其中a是您用原始公式计算的长度。

area_of_triangle :: Float -> Float -> Float -> Float 
area_of_triangle a b c = sqrt(s*(s-a)*(s-b)*(s-c)) 
    where 
    s = (a+b+c)/2 

area :: Float -> Float -> Float -> Maybe Float 
area a b c 
    | ??? = Nothing 
    | ??? = Nothing 
    | ??? = Nothing 
    | otherwise = Just (???) 

我把它作为一个练习找出布尔表达式替换前三??? S,什么替换最后一个???用。

+0

我写了类似这样的https://gist.github.com/logeeker/0fa2ee0bd4c1c1a82456。这段代码无法加载。它说https://gist.github.com/logeeker/27a0f813438cc6fdea95 –

+0

你没有将任何参数传递给'area_of_triangle_codes'的调用。 – chepner

0

我会打破这种分为三个功能:

-- | Takes three numbers and indicates 
-- whether they can be the lengths of 
-- the sides of a (non-degenerate) 
-- triangle. 
triangleInequality :: (Num a, Ord a) 
        => a -> a -> a -> Bool 
triangleInequality x y z 
    | ??? && 
    ??? && 
    ??? = ??? 
    | otherwise = ??? 

uncheckedArea :: RealFloat a 
       => a -> a -> a -> a 
uncheckedArea x y z = ??? 

area :: RealFloat a 
    => a -> a -> a -> Maybe a 
area x y z 
    | ??? = Just ??? 
    | otherwise = Nothing 

this draft article,可以提高你的计算的数值稳定性如下:

area a' b' c' 
    | c - (a - b) <= 0 = Nothing 
    | otherwise = Just $ 0.25 * sqrt ((a+(b+c)) * (c-(a-b)) * (c+(a-b)) * (a+(b-c))) 
    where 
    [c, b, a] = sort [a',b',c'] 

不过,我不不知道GHC是值得信赖的,可以完全按照书面计算,因此可能需要额外的护理。

请注意,为了某些目的,您最好接受0区“三角形”。

0

想通了最终

area_of_triangle :: Float -> Float -> Float -> Maybe Float 
area_of_triangle x y z 
    | x+y>=z && x+z>=y && y+z>=x = Just (sqrt(s*(s-x)*(s-x)*(s-x))) 
    | otherwise = Nothing 
    where 
    s=(x+y+z)/2