3 Replies - 501 Views - Last Post: 14 February 2017 - 10:49 AM

#1 NoYouDidnt  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 55
  • Joined: 04-July 15

Haskell Phone Book

Posted 14 February 2017 - 06:21 AM

I have the following half-implemented functions and types and trying to make a phone book.

type Name = String
type Pnum = Integer
type Pbok = Name -> Maybe Pnum

lookup' :: Pbook -> Name -> Maybe Pnum
lookup' f x = f x

insert :: Pbook -> Name -> Pnum -> Pbook
insert pb x n = 
    if (length . show) n /= 8
    then error "Expected phone number with 8 digits."
    else (\z -> if z == x then Just n else Nothing)

delete :: Pbook -> Name -> Pbook
delete f x = (\x -> Nothing)




The problem is that I know how to pass around the phone book that contains the names. Any help is appreciated!

Is This A Good Question/Topic? 0
  • +

Replies To: Haskell Phone Book

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2504
  • View blog
  • Posts: 3,956
  • Joined: 21-June 11

Re: Haskell Phone Book

Posted 14 February 2017 - 07:24 AM

else (\z -> if z == x then Just n else Nothing)


This is not correct. You're creating a new phone book that contains the mapping x -> n and nothing else. You'll want to use the old phone book (i.e. pb) for keys other than x, instead of just returning Nothing.
Was This Post Helpful? 1
  • +
  • -

#3 NoYouDidnt  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 55
  • Joined: 04-July 15

Re: Haskell Phone Book

Posted 14 February 2017 - 09:45 AM

View Postsepp2k, on 14 February 2017 - 02:24 PM, said:

else (\z -> if z == x then Just n else Nothing)


This is not correct. You're creating a new phone book that contains the mapping x -> n and nothing else. You'll want to use the old phone book (i.e. pb) for keys other than x, instead of just returning Nothing.



Ok so

(\z -> if z == x then Just n else pb z) 


Thank you!
Was This Post Helpful? 0
  • +
  • -

#4 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2504
  • View blog
  • Posts: 3,956
  • Joined: 21-June 11

Re: Haskell Phone Book

Posted 14 February 2017 - 10:49 AM

Exactly.

I just noticed a similar problem in your delete function: Currently it just returns an empty phone book and ignores its parameters. But the function is only supposed to delete a single entry, so you want it to return Nothing when the key is equal to the deleted key and the value from the original phone book otherwise.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1