Advertisement
Guest User

PhoneBook

a guest
Apr 30th, 2015
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.23 KB | None | 0 0
  1. import scala.io.Source
  2.  
  3. object Phonebook extends App {
  4.  
  5.   type ??? = Nothing
  6.  
  7.   //a nice alias for the tuple type representing one entry in the phonebook
  8.   type PhonebookEntry = Tuple5[String, String, String, String, String]
  9.   //another alias for the actual phonebook
  10.   type Phonebook = List[PhonebookEntry]
  11.  
  12.   val regex = """^(0\d+) (\d+) (\w.+?), (.+), (.+)$""".r
  13.  
  14.   def line2Book(line:String, book:Phonebook) = line match {
  15.     case regex(area,number,name,street,city) => (area,number,name,street,city) :: book
  16.     case _ => book
  17.   }
  18.  
  19.   //This function reads the given file and returns a list of entries (=tuples)
  20.   def fileToPhoneBook(filename: String):Phonebook =
  21.     Source.fromFile(filename).getLines().foldRight[Phonebook](Nil)(line2Book)
  22.  
  23.   //Read the file
  24.   val phoneBook = fileToPhoneBook("./src/files/phonebook.txt")
  25.  
  26.   //print all entries in the phonebook
  27.   phoneBook foreach println
  28.  
  29.   //This function returns a list containing all names of people living in the specified city
  30.   def peopleLivingIn(book: Phonebook, city:String) =
  31.     //book.filter(entry => entry._5 == city)
  32.     book.filter(_._5 == city)
  33.  
  34.   println("People living in Graz")
  35.   peopleLivingIn(phoneBook, "Graz") foreach println
  36.  
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement