# Get a value based on input value

Hi,

I have created a below syntax to get a list of values.
def primeNum(n:Int) = (1 to 1000).filter(i =>i % 2 !=0 && (i > 2))
I am trying to get dynamically value from the result if I pass i/p n to any value(if n = 5 i need to get 5th value from result. If I pass n=7 i need to get 7th position value)
I am not able to get how to pass make it dynamically based based on input value.
Can some suggest.

Regards,
Kumar

Howdy! I believe you are looking for the `apply()` function, which is simply expressed as parentheses in Scala – that returns the nth value in a sequence. See for example this fiddle:

``````def chosen(i: Int) = (10 to 20)(i)
println(chosen(5))
> 15
``````

Thanks for your reply. I have to calculate prime number first then if I pass input accordingly that prim number should be printed

Can anyone provide me a suggestion on this.

The suggestion was to Google it, and you were asked what you had already researched / Googled… you didn’t respond, you just came back asking for an answer again. I think you would get more useful responses if you spent some time explaining what you’ve already tried to solve the problem on your own, so that we know the right direction in which to point you.

you can use lazy evaluation
it can be done by using stream (scala 2.12), or lazy list, or view (operation in scala 2.13)
for excample:

``````def primeNum(n: Int) = (1 to 1000).view // it become lazy evaluated
.filter(i => i % 2 != 0 && (i > 2))

``````

sure it also can be done by usin’ recursion

Hi ,

Thanks a lot for your reply. I am trying to resolve this issue.
I think 15 is not a prime number.
We need to exclude these numbers as well.

I think 15 is not a prime number.

yes it’s not a prime number, just a sample for lazy evaliation

You are getting a lot of feedback on how to use the language; if you need information on how to identify prime numbers, there are well-known, language-agnosticn algorithms available; which one you choose depends on how your implementation will be used, which is what makes it so hard for us to help you without having more context around how you will be using this in a production code base.

Take a look at the console API. There are some clues within…

https://www.scala-lang.org/api/current/scala/Console\$.html

Are you asking for interactive input from the user? If so, I wrote the following little function that prompts the user for a value. For convenience, it provides a default value that the user can select by simply hitting return.

``````  def enter( // prompt user to enter input
label: String = "", // label for requested input
default: String = ""): // default value to return if nothing entered
String = {

print("enter " + label + " [" + default + "]: ")
if (entry == "") default else entry
}

def stop() = { // breakpoint for debugging
print("\nhit <enter> to continue ")
`val number = enter("number", 2).toInt`