4

私は余弦定理関数の法則を実装しようとしています、そしてここに私のコードがあります:

cosC :: [a] -> a
cosC sides
   | length sides < 3          = 0
   | otherwise                 = (x ^ 2 + y ^ 2 - z ^ 2) / (2 * x * y)
   where x = head(tail(tail(sides)))
         y = head(tail(sides))
         z = head(sides)

しかし、2つのエラーが発生します。

No instance for (Fractional a)
arising from a use of `/'
In the expression: (x ^ 2 + y ^ 2 - z ^ 2) / (2 * x * y)
In an equation for `cosC':
    cosC sides
      | length sides < 3 = 0
      | otherwise = (x ^ 2 + y ^ 2 - z ^ 2) / (2 * x * y)
      where
          x = head (tail (tail (sides)))
          y = head (tail (sides))
          z = head (sides)

No instance for (Num a)
arising from the literal `2'
In the first argument of `(*)', namely `2'
In the first argument of `(*)', namely `2 * x'
In the second argument of `(/)', namely `(2 * x * y)'

編集:上記の余弦定理の記号のタイプミスを修正しました。それを指摘してくれたDanielFischerに感謝します。

4

2 に答える 2

11

一般的なタイプ から数値結果を計算しようとしていますがa、これはおそらく機能しません。(これは、一般的な道路車両だけでなく、宇宙船、超高層ビル、ペーパークリップ、中性子星などの一般的なもののために橋を架けようとするようなものです)Floating次の項目に制約を追加するだけです。

cosC :: Floating a => [a] -> a

そして、そのような計算に必要な算術演算を実行できます。(Fractional実際にはこの関数には十分ですが、結果のを計算することはできませんarccos)。


あなたの問題とは関係なく、Haskellでリストを分解するもっと良い方法があることに注意してください:

cosC (x:y:z:_) = (x^2 + y^2 - z^2) / (2*x*y)
cosC _ = 0

あなたの定義と同等です。とにかく、なぜあなたは議論をリストとして取っているのですか?それはかなりLispっぽいことです、Haskellでは私は好きです

cosC :: Floating a => a -> a -> a -> a
cosC x y z = (x^2 + y^2 - z^2) / (2*x*y)
于 2012-11-30T13:20:31.717 に答える
5

cosC :: Fractional a => [a] -> a

そして、これはあなたが(で)見つけることができる方法ですghci

*Main> let fun [x, y, z] = (x * x + y * y + z * z) / (2 * x * y)
*Main> :type fun
fun :: Fractional a => [a] -> a
于 2012-11-30T13:20:17.537 に答える