Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.io.Source
- object Phonebook extends App {
- type ??? = Nothing
- //a nice alias for the tuple type representing one entry in the phonebook
- type PhonebookEntry = Tuple5[String, String, String, String, String]
- //another alias for the actual phonebook
- type Phonebook = List[PhonebookEntry]
- val regex = """^(0\d+) (\d+) (\w.+?), (.+), (.+)$""".r
- def line2Book(line:String, book:Phonebook) = line match {
- case regex(area,number,name,street,city) => (area,number,name,street,city) :: book
- case _ => book
- }
- //This function reads the given file and returns a list of entries (=tuples)
- def fileToPhoneBook(filename: String):Phonebook =
- Source.fromFile(filename).getLines().foldRight[Phonebook](Nil)(line2Book)
- //Read the file
- val phoneBook = fileToPhoneBook("./src/files/phonebook.txt")
- //print all entries in the phonebook
- phoneBook foreach println
- //This function returns a list containing all names of people living in the specified city
- def peopleLivingIn(book: Phonebook, city:String) =
- //book.filter(entry => entry._5 == city)
- book.filter(_._5 == city)
- println("People living in Graz")
- peopleLivingIn(phoneBook, "Graz") foreach println
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement