2016-09-22 11 views
1

私はハスケルに新しいです、私は下の答えを見回しましたが、運がありませんでした。Haskell - データ型の結合?

なぜこのコードはコンパイルされませんか?

newtype Name = Name String deriving (Show, Read) 
newtype Age = Age Int deriving (Show, Read) 
newtype Height = Height Int deriving (Show, Read) 

data User = Person Name Age Height deriving (Show, Read) 

data Characteristics a b c = Characteristics a b c 

exampleFunction :: Characteristics a b c -> User 
exampleFunction (Characteristics a b c) = (Person (Name a) (Age b) (Height c)) 

エラー:

"Couldn't match expected type ‘String’ with actual type ‘a’,‘a’ is a rigid type, variable bound by the type signature" 

しかし、これはうまくコンパイル:

exampleFunction :: String -> Int -> Int -> User 
exampleFunction a b c = (Person (Name a) (Age b) (Height c)) 

私は上記を行うためのシンプルな方法があります実現が、私はただの異なる使用をテストしていますカスタムデータ型。

更新:

私の傾きがそのタイプセーフではないので、コンパイラは「exampleFunction ::特性B C」を好きではないということです。すなわち、私はa == Name String、b == Age Int、c == Height Intの保証を提供していません。

答えて

6

exampleFunctionが一般的です。 タイプa,b、およびcの値がCharacteristics a b cであると主張しています。ただし、タイプaの値はNameに渡されます。の値はStringの値になります。解決策は、特性が実際にどのようなタイプであるかを特定することである。

exampleFunction :: Characteristics String Int Int -> User 
exampleFunction (Characteristics a b c) = (Person (Name a) (Age b) (Height c)) 

ここでもnewtypeは必要ありません。シンプルなタイプのエイリアスで十分です。

type Name = String 
type Age = Int 
type Height = Int 

type Characteristics = (,,) 

exampleFunction :: Characteristics Name Age Height -> User 
exampleFunction (Charatersics n a h) = Person n a h 
+0

おかげで、私はほとんどこれと同時に、私の質問を更新し、いくつかの説明を追加し、エラーを説明していない:P –

2

このお試しください:この作品

exampleFunction :: Characteristics String Int Int -> User 
exampleFunction (Characteristics a b c) = (Person (Name a) (Age b) (Height c)) 

理由を、そしてあなたは、名前、年齢と身長はあなたの例の機能が完全に汎用的な引数を取り、特定のタイプを必要とすることであることはありません。

例のこの行のa、b、およびcは、引数のタイプであり、その名前ではありません。

exampleFunction :: Characteristics a b c 
+0

これはちょうど – jarandaf

+0

:-)コンパイラを下にピタッ –