2016-04-12 13 views
-1

次の関数を実行しようとすると、エラーが発生します。Haskell:list comprehension:制約の中の非可変引数:Num [t]

Prelude> let squareSum list = [result | (x, y, z) <- list, result <- x^2 + y^2 + z^2] 

<interactive>:4:5: 
    Non type-variable argument in the constraint: Num [t] 
    (Use FlexibleContexts to permit this) 
    When checking that ‘squareSum’ has the inferred type 
    squareSum :: forall t. Num [t] => [([t], [t], [t])] -> [t] 

いくつかのいずれかがこの問題を解決するためにどのように、私を説明できますか?このエラーは正確に何に伝えられていますか?

+2

これはおそらく、あなたが* sum *から 'result'を引き出すことを試みているからです - let squareSum list = [x^2 + y^2 + z^2 | (x、y、z)< - リスト] '? – Carsten

+0

Carstenに感謝します。私は試しましたが、それでも同じ問題に直面しています。 Prelude> let squareSum list = [x^2 + y^2 + z^2 | (X、Y、Z)< - リスト] プレリュード> squareSum [1、2、3] :33:1:制約に ノン型可変引数:民(T、T、T) (これを許可するにはFlexibleContextを使用してください) 'it'に推論された型があることを確認すると、 it :: forall t。 (Num t、Num(t、t、t))=> [t] –

+0

あなたのタプルを最初に定義した方法は、 '[(1,2,3)、4 、5,6)] ' – Carsten

答えて

5

元の質問

あなたが投稿:

Prelude> let squareSum list = [result | (x, y, z) <- list, result <- x^2 + y^2 + z^2] 

<interactive>:3:5: 
    Non type-variable argument in the constraint: Num [t] 
    (Use FlexibleContexts to permit this) 
    When checking that ‘squareSum’ has the inferred type 
     squareSum :: forall t. Num [t] => [([t], [t], [t])] -> [t] 

はこれが原因で値のソースとしてそれを使用して、リストでなければならない計算x^2 + y^2 + z^2ある推論から来ていますリストの理解(result <- ...)。それがリストであれば、数学演算子はリスト型の値を超えています。つまり、初期変数であるlistはリストのタプルリスト([([t],[t],[t])])でなければならず、各リストは何らかの形で有効な数字(Num [t])でなければなりません。

コメント質問

Prelude> let squareSum list = [ x^2 + y^2 + z^2 | (x, y, z) <- list] 
Prelude> squareSum [1,2,3] 

<interactive>:9:1: 
    Non type-variable argument in the constraint: Num (t, t, t) 
    (Use FlexibleContexts to permit this) 
    When checking that ‘it’ has the inferred type 
     it :: forall t. (Num t, Num (t, t, t)) => [t] 

今、あなたは、変数listはタプル((x, y, z) <- list)が含まれていると言うが、その後、あなたは[1,2,3]としてリストを定義します。両方を満たすために、1,2および3の数値リテラルは、タプルを表す必要があります。これは、クラスインスタンスNum (t, t, t)を定義した場合に可能です。

あなたが

を欲しいものカーターは、すでにあなたのソリューションを語っていますが、賢明なリストには適用されませんでした。どうやって解決策を定義し、明示的な型を与えて混乱が少ないのでしょうか?

Prelude> :{ 
Prelude| let squareSum :: [(Int,Int,Int)] -> [Int] 
Prelude|  squareSum list = [ x^2 + y^2 + z^2 | (x, y, z) <- list] 
Prelude| :} 
Prelude> squareSum [(1,2,3), (4,5,6)] 
[14,77] 

成功!私たちは2つのタプルを提供し、2つのInt結果を得ました。

-1

次のスニペットは私の問題を解決しました。

Prelude> let processData fun list = [y | x <- list, let y = fun x] 
Prelude> let sumSquare (x, y, z) = x^2 + y^2 + z^2 
Prelude> 
Prelude> processData sumSquare [(1, 2, 3), (4, 5, 6)] 
[14,77]