2017-12-22 19 views
2

私は以下のエラーが発生しています。私はすべての再帰的なケースを想定しています。haskell非網羅的なパターンがありません

Prelude> product [] =1 
Prelude> product (x:xs) =x * product xs 
Prelude> product [1,2,3] 
*** Exception: <interactive>:48:1-30: Non-exhaustive patterns in function product 

答えて

8

GHCiのは、個別の行を処理しますが、機能に

product [] = 1 

を定義した後、これを修正するには

product (x:xs) = x * product xs 

新しい関数を定義することによって、productを影にしているので、あなたが使用することができます:{複数行ブロックの場合は:}

:{ 
product [] = 1 
product (x:xs) = x * product xs 
:} 

またはこれが私の推奨するものです。関数定義をファイルに入れ、GHCiにロードしてください。

+3

と書くか、1行で書くことができます: 'product [] = 1; product(x:xs)= x * product xs' –

2

-Wallで警告をオンにすることを強くお勧めします。そうすることで、ここでは、各定義が別々に考慮されるという事実を示唆します。実際

> :set -Wall 
> product [] = 1 

<interactive>:2:1: warning: [-Wincomplete-patterns] 
    Pattern match(es) are non-exhaustive 
    In an equation for ‘product’: Patterns not matched: (_:_) 
> product (x:xs) = x * product xs 

<interactive>:3:1: warning: [-Wincomplete-patterns] 
    Pattern match(es) are non-exhaustive 
    In an equation for ‘product’: Patterns not matched: [] 

[]についての最後の警告の苦情が最初の定義 product []が無視されたことを示し、一致していないか注意してください。

関連する問題