0
votes

I have the following two type definitions in Haskell which are from Thompsons 'Craft of Functional Programmingi', Second Edition, 1999.

type ShopItem = (String,Int)
type Basket   = [ShopItem]

When I try to create my own 'selector function' on these types as such:

name  :: ShopItem -> String
price :: ShopItem -> Int

GHCI gives me the following error.

The type signature for ‘name’ lacks an accompanying binding

Why isn't 'name' bound to the String element of the ShopItem tuple and likewise for 'price'?

Is this older syntax that is no longer acceptable in the current version of GHCI? I'm using version 7.10.3 on current Linux Mint 18.

1
GHCi is just telling you that you've only written down the signatures for two selector functions name and price but without writing the implementation. - Alec

1 Answers

3
votes

You need to specify the implementations of name and price:

name :: ShopItem -> String
name (n, _) = n

price :: ShopItem -> Int
price (_, p) = p

You could also use data instead of type, and use record notation:

data ShopItem = ShopItem { name :: String, price :: Int }

Then these can be used to extract fields:

item = ShopItem { name = "Beans", price = 2 }
-- or
item = ShopItem "Beans" 2

name item  ==  "Beans"

But also to replace them:

item { price = 4 }  ==  ShopItem { name = "Beans", price = 4 }