Search code examples
scalayieldfor-comprehension

Scala beginner for-comprehensions and functions


Hey guys i am new to scala and i dont knowe what i am doing wrrong to get the right typ into the yield statement:

def prim(n:Int): (Boolean, List[Int]) = divsers(n) -> List(1,n) //flatMap for-comprehensions

def divsers(n:Int):Boolean=
 (for{
    d <- 1 to n
    if((n%d)->0)
   }yield(d) // <- what i need to put here to make it work with the function prim?
  )
 prim(11);

I just want to test if a number is a prime number. I realy have to say that i got realy problems with the syntac and typs.Even if i put just "true" in yield it dont work?


Solution

  • You're doing all kinds of things that make no sense.

    divsers(n) -> List(1,n) What is the point of returning a tuple who's 2nd element is a List of 2 Ints? The 1st Int is always 1 and the 2nd Int is always the number passed as an argument to prim().

    if((n%d)->0) You've created another tuple here. You probably mean to say if (n%d) > 0.

    yield ? The for comprehension is walking through a sequence of numbers from 1 to n. Some of them will pass through your if condition and some won't. Now you've got a new list of numbers. How you're supposed to turn that into a Boolean is up to you.