Ash
Ash

Reputation: 9061

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!

Upvotes: 2

Views: 155

Answers (2)

hammar
hammar

Reputation: 139830

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.

Upvotes: 3

sepp2k
sepp2k

Reputation: 370082

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].

Upvotes: 5

Related Questions