开发者

Add an item of my own type to a list in Haskell?

I need to add my own data type to a list开发者_开发技巧 which is in a function, here's my code:

type Car = (String, String, Int, String)

testDatabase :: [Car] 
testDatabase = [("Ford", "Petrol", 2006, "Sport")]

addNewCar :: Car 
addNewCar newCar = newCar:testDatabase

Here's the error I get:

ERROR file:.\template.hs:20 - Type error in explicitly typed binding
*** Term : addNewCar
*** Type : ([Char],[Char],Int,[Char]) -> [([Char],[Char],Int,[Char])]
*** Does not match : Car

(sorry its a rubbish explanation im just struggling a tad with Haskell). Thank you in advance!!

Ash!


The inferred type of addNewCar is ([Char],[Char],Int,[Char]) -> [([Char],[Char],Int,[Char]), which is the same as Car -> [Car]. This type says that addNewCar is a function which takes a car and returns a list of cars. This is exactly the type you want.

However your type signature says that addNewCar is simply a value of type Car. This is wrong and clashes with the inferred type. That's why you get the error. So to fix this, simply remove the type signature or change it to addNewCar :: Car -> [Car].


You have a type error in your code. addNewCar is a function that takes a car and returns a list of cars, so it should have the type

addNewCar :: Car -> [Car]

You could also just remove the type signature, and the compiler will infer it automatically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜