2016-03-17 48 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