2

Suppose I've got a list of functions List[A => B] and need a function that returns List[B] for a given value of type A:

def foo[A, B](fs: List[A => B]): A => List[B] = a => fs.map(_.apply(a))

Is there any simpler (maybe with cats) way to write List[A => B] => A => List[B] ?

Michael
  • 41,026
  • 70
  • 193
  • 341
  • 3
    You can do `a => fs ap List(a)` with `cats` or just write `fs.map(_(a))`, but I doubt it is really making it simpler. – Oleg Pyzhcov Jul 18 '17 at 07:45
  • I concur it maybe does not make it simple but it's good to know anyway ! So, thank you, Oleg. – Michael Jul 18 '17 at 09:55

2 Answers2

3

As @Oleg points out, you can use Applicative to generate the function:

import cats.implicits._

def foo[A, B](fs: List[A => B]): A => List[B] = a => fs ap List(a)

Although I don't think it makes much of a difference in this particular case.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
1

The signature of f (a -> b) -> a -> f b suggests to use flap (from Haskell).

Starting from 2.9.0 you can use its equivalent in Cats named mapApply.

import cats.implicits._

def foo[A, B](fs: List[A => B]): A => List[B] = a => fs.mapApply(a)
Max Smirnov
  • 477
  • 3
  • 10