Functional equivalent of if (p(f(a), f(b)) a else b

Posted by oxbow_lakes on Stack Overflow See other posts from Stack Overflow or by oxbow_lakes
Published on 2010-02-19T08:55:18Z Indexed on 2010/03/13 6:45 UTC
Read the original article Hit count: 137

I'm guessing that there must be a better functional way of expressing the following:

def foo(i: Any) : Int

if (foo(a) < foo(b)) a else b 

So in this example f == foo and p == _ < _. There's bound to be some masterful cleverness in scalaz for this! I can see that using BooleanW I can write:

p(f(a), f(b)).option(a).getOrElse(b)

But I was sure that I would be able to write some code which only referred to a and b once. If this exists it must be on some combination of Function1W and something else but scalaz is a bit of a mystery to me!

EDIT: I guess what I'm asking here is not "how do I write this?" but "What is the correct name and signature for such a function and does it have anything to do with FP stuff I do not yet understand like Kleisli, Comonad etc?"

© Stack Overflow or respective owner

Related posts about scala

Related posts about functional-programming