Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 683
Native Avatar asked Aug 24 '26 21:08

Native


1 Answers

Scala map works over an elements rather than whole collection. Try this:

val floor = source.map {
    case '(' => 1
    case ')' => -1
}.sum
like image 175
vsminkov Avatar answered Aug 26 '26 14:08

vsminkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!