0

How can we accept function name as user input? Is there any member in standard library ​like readLine, readByte, etc that solves the purpose?

Context: As part of functional programming, I need to pass function name as first argument but instead of hardcoding I want to accept it as user input.

Please suggest.

Here is the sample code:

def square(x:Int):Int = x*x

def sum(f: Int => Int, a:Int, b:Int):Int ={
  if(a>b) 0 else f(a) + sum(f,a+1,b)
}

println("Enter the first number:")

var num1 = readInt()

println("Enter the second number:")

var num2 = readInt()

val ressum = sum(square,num1,num2)
4
  • There's a big difference between passing the function name and passing the function itself. Are you sure you don't actually want the latter, given that your context is functional programming practice? Passing the function name as a string is hardly idiomatic FP. Commented Jan 25, 2018 at 5:09
  • Can you explain a bit what you want to achieve. Do you want user to enter the function name and then from code you want to execute that function? Commented Jan 25, 2018 at 5:16
  • refer sample code I have added Commented Jan 25, 2018 at 11:07
  • you could use reflection to do this, but reflection should really be considered a last resort, I would strongly suggest going with jwvh's approach unless there's a really, really strong reason it's unsatisfactory Commented Jan 25, 2018 at 23:12

1 Answer 1

2

User input is a String. Function and method names are not. To go from one to the other you have to test the input content.

val result = usrInput match {
  case "foo" => foo()
  case "bar" => bar()
  case "baz" => baz()
  case _ => throw new Error(s"I don't know $usrInput")
}

This assumes that they all have the same return type (and the returned value is of interest). If they return different types then the code gets more convoluted.

if (usrInput == "foo") {
  val fooRslt = foo()
  // do more "foo" stuff
} else if (usrInput == "bar") {
  val barRslt = bar()
  // etc. etc.
...

Function and method calls are checked for type safety by the compiler. User input is runtime content. Compile-time, run-time, ne'er the twain shall meet.

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

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.