mardi 9 août 2016

How do I use pattern matching for elements within a list?

I'm working on Advent of Code's coding challenges and I'm on day one. I've read from a file that contains nothing but ((()(())(( so I'm looking to turn each '(' to 1 and each ')' to a -1 so I can compute them. But I'm having issues when I map findFloor over source. I'm getting a type mismatch. Everything looks right to me and that's the weird part because it's not working.

import scala.io._

object Advent1 extends App {

// Read from file
val source = Source.fromFile("floor1-Input.txt").toList

// Replace each '(' with 1 and each ')' with -1, return List[Int]
def findFloor(input: List[Char]):Int = input match {

        case _ if input.contains('(') => 1
        case _ if input.contains(')') => -1 

}

val floor = source.map(findFloor)   

}

Error output

error: type mismatch;

found : List[Char] => Int

required: Char => ?

val floor = source.map(findFloor) ^ one error found

What I'm I doing wrong here ? / what I'm I missing ?

Aucun commentaire:

Enregistrer un commentaire