2016-10-29 11 views
3

このコードに問題があります。私は2つのリストを取り、リストBの対応する要素でリストAの各要素を分割しようとする単純な関数を書こうとしています。リストBの要素が0の場合はNothingを返す必要があり、そうでない場合はJust (a/b)を返します。ここでハスケルコードzipを使用した場合は

は、コードは次のとおりです。

divlist :: Integral a => [a] -> [a] -> [Maybe a] 
divlist = zipWith (\x y -> if (y /= 0) then Just (x/y) else Nothing) 

それはおそらく愚かなものだが、私は単にそれを見つけることができません。

EDIT:

C:\Users\spravce\Desktop\Haskell\6.hs:16:51: error: 
    • Could not deduce (Fractional a) arising from a use of ‘/’ 
    from the context: Integral a 
     bound by the type signature for: 
       divlist :: Integral a => [a] -> [a] -> [Maybe a] 
     at C:\Users\spravce\Desktop\Haskell\6.hs:14:1-48 
    Possible fix: 
     add (Fractional a) to the context of 
     the type signature for: 
      divlist :: Integral a => [a] -> [a] -> [Maybe a] 
    • In the first argument of ‘Just’, namely ‘(x/y)’ 
    In the expression: Just (x/y) 
    In the expression: if (y /= 0) then Just (x/y) else Nothing 
Failed, modules loaded: none. 

EDIT 2: をdiv x y代わりにx/yを使用すると、ちょうどそれをやったこれは、GHCiのが報告されているものです。 :)ありがとう。

答えて

7

関数にはIntegralという制約が指定されていますが、小数除算を表す関数内には(/)が使用されています。

おそらくdivを使用します。 3 `div` 2 == 1。それ以外の場合は、制約をIntegralからFractionalに変更します(エラーメッセージの指示)。

関連する問題