Scala: Higher order function to return the union of sets

158 views Asked by At

I am working on the following scala higher order function:

def after(M: Set[Expression], n: String): Set[Set[Expression]] = { M.map((expr: Expression) => aft(expr,n)) }

The function aft has the following signature:

def aft(m: Expression, n: String): Set[Expression]

The type Expressionis an abstract class which I created.

I want the method after to take a set M of Expressions, apply the aft on each element in M and then return the union of the results (i.e. a Set[Expression] rather than a Set[Set[Expression]]). I think that a higher order function should be used in this case but I can't really understand how to do it as I still consider myself a novice in Scala and functional programming.

1

There are 1 answers

2
Yuval Itzchakov On BEST ANSWER

You're looking for flatMap instead of map:

def after(M: Set[Expression], n: String): Set[Expression] = { M.flatMap((expr: Expression) => aft(expr,n)) }

In general for any user defined type to behave as expected with Set[A], one needs to make sure hashCode and equals are properly implemented, otherwise equality between two objects will use Object.equals, which is usually not what you want.

As a side note, although this is a lovely method, it isn't a higher order function. It doesn't take a function as an argument and doesn't return a function.