2

I'm just not understanding how to build a function from previous functions.

For example, math.min() function that takes the minimum of two numbers. What if I wanted to create a function min3Z(a:int, b:int, c:Int)? How would I build this from min?

1

2 Answers 2

7

Your question is unclear. Are you simply trying to utilize math.min() in min3Z()? Because in that case, you can do:

def min3Z(a: Int, b: Int, c: Int) = math.min(a, math.min(b, c))

If you want to pass in an arbitrary function (for example, making it so you can specify max or min), you can specify a function as a parameter:

def min3Z(a: Int, b: Int, c: Int, f: (Int, Int) => Int) = f(a, f(b, c))

The syntax (Int, Int) => Int in Scala is the type for a function that takes two parameters of type Int and returns a result of type Int. math.min() and math.max() both fit this criteria.

This allows you to call min3Z as min3Z(1, 2, 3, math.min) or min3Z(1, 2, 3, math.max). It's even possible to make a version of min3Z() that takes an arbitrary number of Ints and an arbitrary (Int, Int) => Int function, but that's beyond the scope of your question.

Sign up to request clarification or add additional context in comments.

Comments

0

If implementing min for three values is your specific case you may want to generalize to an arbitrary number of arguments by using a variadic (aka varargs) function as follows:

def min(xs: Int*): Int = xs.min

The variadic syntax is denoted by the * symbol after the type declaration--Int in this case. This way all the following calls would work:

min(1, 2)
min(1, 2, 3, 4, 5, 6, -1)
// and so on...

Talking about being generic you could also write an even more generic min that accepts any numeric type, not only Int ones:

def min[T : Numeric](xs: T*): T = xs.reduceLeft(implicitly[Numeric[T]].min)

An use it as follows:

min(1, 2, 3, 4)
min(1.2, 3.4, 5.6, 4.2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.