Type Mismatch Unit and String in Scala - scala

I am trying to take from a list of tuples (e.g. List[(String, String)]) some words that have the difference between the number of syllables smaller than 2.
If that is ok, I return them - however, I have some issues: I get Unit found and String expected.
def ecrire():String = {
// Choose deux output: List[(Word, Word)]
// I take every tuple of the list and proceed as the element "b"
for (b <- choose_deux()){
val x = b._1
val y = b._2
val diff = Math.abs(x.syllabes - y.syllabes)
// Check if difference between syllables is smaller than 2
if(diff <= 2)
return x.toString() + "\n" + y.toString()
}
}
}
Now I know that probably I have to do a yield at the bottom, but yield what exactly? The idea is that if the condition shown in the "if" is respected, I write the string made of these two elements.
The error is shown at the for loop: type mismatch; found: Unit; required: String
Could you please help me a bit? I am still new and learning!

Type mismatch error is because your for loop doesn't have else statement and you can't return using if inside a for loop. So for loop is not returning anything so scala compiler assumes the return type to be () i.e. unit() and you have defined the return type as String.
Defining the functions in the following way should solve your issue
def diff(x) = Math.abs(x._1.syllabes - x._2.syllabes)
for (b <- choose_deux() if(diff(b) <= 2)) yield b._1.toString() + "\n" + b._2.toString()

Related

Set of WrappedArray: Type arguments [Int] do not conform to method empty's type parameter bounds [T <: AnyRef]

I'm trying to make a function that calculates how many combinations of elements with repetition there are given an array of values and a exact sum value.
But I'm getting an error:
Error:(23, 38) type arguments [Int] do not conform to method empty's type parameter bounds [T <: AnyRef]
r(maxValue,WrappedArray.empty[Int],Set[WrappedArray[Int]]()).size
It seems there is a type problem in the empty set I'm trying to pass to the function.
I choosed WrappedArrays following this [question]: Scala: lightweight way to put Arrays in a Set or Map in order to be able to have a set of arrays without duplicates.
import scala.collection.mutable.WrappedArray
def Combinations(maxValue: Int): Int = {
val values= Array(1,2,5,10)
def r (a:Int,can:WrappedArray[Int],sol:Set[WrappedArray[Int]]): Set[WrappedArray[Int]] ={
values.map(x=> if (a-x > 0) r(a-x,can:+x,sol) else if (a-x == 0) sol + (can:+x).sorted else sol).reduce((x, y)=>x union y)
}
r(maxValue,WrappedArray.empty[Int],Set[WrappedArray[Int]]()).size
}
Combinations(4)
Thanks
WrappedArray.empy is bounded by AnyRef, as Int inherits from AnyVal you cannot declare your wrappedArray this way.
However you can declare your empty array this way new WrappedArray.ofInt(Array())
Here is a little fiddle for you
https://scalafiddle.io/sf/PioRREd/0
I've never seen anyone ever importing WrappedArray for anything. It's a rather obscure implementation detail for providing collection methods on ordinary arrays, it has no place in the solution of combinatoric problems. Another general remark: methodNames are written in camel-case, starting with a lowercase letter.
Here is a more idiomatic (and also much simpler) solution:
def numCombinations(
sum: Int,
coins: List[Int] = List(1, 2, 5, 10)
): Long = {
coins match {
case Nil => if (sum == 0) 1L else 0L
case h :: t => {
(0 to sum / h)
.map { i => numCombinations(sum - i * h, t) }
.sum
}
}
}
println(numCombinations(4))
Example: for n = 4, it will find the combinations
1 + 1 + 1 + 1
1 + 1 + 2
2 + 2
and output 3.

Getting an error trying to map through a list in Scala

I'm trying to print out all the factors of every number in a list.
Here is my code:
def main(args: Array[String])
{
val list_of_numbers = List(1,4,6)
def get_factors(list_of_numbers:List[Int]) : Int =
{
return list_of_numbers.foreach{(1 to _).filter {divisor => _ % divisor == 0}}
}
println(get_factors(list_of_numbers));
}
I want the end result to contain a single list that will hold all the numbers which are factors of any of the numbers in the list. So the final result should be (1,2,3,4,6). Right now, I get the following error:
error: missing parameter type for expanded function ((x$1) => 1.to(x$1))
return list_of_numbers.foreach{(1 to _).filter {divisor => _ % divisor == 0}}
How can I fix this?
You can only use _ shorthand once in a function (except for some special cases), and even then not always.
Try spelling it out instead:
list_of_numbers.foreach { n =>
(1 to n).filter { divisor => n % divisor == 0 }
}
This will compile.
There are other problems with your code though.
foreach returns a Unit, but you are requiring an Int for example.
Perhaps, you wanted a .map rather than .foreach, but that would still be a List, not an Int.
A few things are wrong here.
First, foreach takes a function A => Unit as an argument, meaning that it's really just for causing side effects.
Second your use of _, you can use _ when the function uses each argument once.
Lastly your expected output seems to be getting rid of duplicates (1 is a factor for all 3 inputs, but it only appears once).
list_of_numbers flatMap { i => (1 to i) filter {i % _ == 0 }} distinct
will do what you are looking for.
flatMap takes a function from A => List[B] and produces a simple List[B] as output, list.distinct gets rid of the duplicates.
Actually, there are several problems with your code.
First, foreach is a method which yields Unit (like void in Java). You want to yield something so you should use a for comprehension.
Second, in your divisor-test function, you've specified both the unnamed parameter ("_") and the named parameter (divisor).
The third problem is that you expect the result to be Int (in the code) but List[Int] in your description.
The following code will do what you want (although it will repeat factors, so you might want to pass it through distinct before using the result):
def main(args: Array[String]) {
val list_of_numbers = List(1, 4, 6)
def get_factors(list_of_numbers: List[Int]) = for (n <- list_of_numbers; r = 1 to n; f <- r.filter(n%_ == 0)) yield f
println(get_factors(list_of_numbers))
}
Note that you need two generators ("<-") in the for comprehension in order that you end up with simply a List. If you instead implemented the filter part in the yield expression, you would get a List[List[Int]].

Char.type vs Char in Scala

I have the following code:
def findNonEqualTuples(value: String): List[(Char, Char)] = {
val result = ListBuffer((Char,Char))
for (current <- 0 until value.length / 2) {
if (!value.charAt(current).equals(value.charAt(value.length - 1 - current))) {
val tuple = (value.charAt(current), value.charAt(value.length - 1 - current))
result += tuple
}
}
return result.toList
}
The line result += tuple says "Type mismatch, expected: (Char.type, Char.type) actual: (Char, Char)". I am quite new to scala. Could someone explain what is the difference between these two types and how I fix it?
Your problem is in how you declare the result ListBuffer. Try:
val result = ListBuffer[(Char,Char)]()
Square-bracket notation is used for specifying parameter types. The compiler's interpretation of your code is that you want to create a new ListBuffer initialised to contain the tuple (Char, Char), that is, a tuple containing the Char type (more accurately, as noted by #LuigiPlinge, it is the Char companion object - paired with itself) - hence the mismatch error.
EDIT - addressing the question in your comment:
this is a different type of braces issue :)
The key is to remember that even operators in Scala are in fact method calls,
so that result += (...) is actually sugar for:
result = result.+(...) // since "op=" is sugar for x = x op ...
ie. calling the += method with the arguments contained within the parentheses. So, to pass a single argument consisting of a tuple, we need an extra set of parentheses:
result += ((value.charAt(current), value.charAt(value.length - 1 - current)))
The outer parentheses delimit the method's parameter list, while the inner parentheses encapsulate the tuple.

Scala - Type Mismatch Found Unit : required Array[Int]

Why does the method give a compile error in NetBeans
( error in question -- Type Mismatch Found Unit : required Array[Int] )
def createArray(n:Int):Array[Int] =
{
var x = new Array[Int](n)
for(i <- 0 to x.length-1)
x(i) = scala.util.Random.nextInt(n)
}
I know that if there was a if clause - and no else clause - then why we get the type mismatch.
However, I am unable to resolve this above error - unless I add this line
return x
The error is not happening because the compiler thinks what happens if n <= 0
I tried writing the function with n = 10 as hardcoded
Thoughts ?
Your for comprehension will be converted into something like:
0.to(x.length - 1).foreach(i => x(i) = scala.util.Random.nextInt(i))
Since foreach returns (), the result of your for comprehension is (), so the result of the entire function is () since it is the last expression.
You need to return the array x instead:
for(i <- 0 to x.length-1)
x(i) = scala.util.Random.nextInt(n)
x
Yet another one,
def createArray(n: Int): Array[Int] = Array.fill(n) { scala.util.Random.nextInt(n) }
Then, for instance
val x: Array[Int] = createArray(10)
You could do something cleaner in my own opinion using yield :
def createArray(n:Int):Array[Int] =
(for(i: Int <- 0 to n-1) yield scala.util.Random.nextInt(n)).toArray
This will make a "one lined function"

Scala for comprehension of sequence inside a Try

I am writing a Scala program in which there is an operation that creates a sequence. The operation might fail, so I enclose it inside a Try. I want to do sequence creation and enumeration inside a for comprehension, so that a successfully-created sequence yields a sequence of tuples where the first element is the sequence and the second is an element of it.
To simplify the problem, make my sequence a Range of integers and define a createRange function that fails if it is asked to create a range of an odd length. Here is a simple for comprehension that does what I want.
import scala.util.Try
def createRange(n: Int): Try[Range] = {
Try {
if (n % 2 == 1) throw new Exception
else Range(0, n)
}
}
def rangeElements(n: Int) {
for {
r <- createRange(n)
x <- r
} println(s"$r\t$x")
}
def main(args: Array[String]) {
println("Range length 3")
rangeElements(3)
println("Range length 4")
rangeElements(4)
}
If you run this it correctly prints.
Range length 3
Range length 4
Range(0, 1, 2, 3) 0
Range(0, 1, 2, 3) 1
Range(0, 1, 2, 3) 2
Range(0, 1, 2, 3) 3
Now I would like to rewrite my rangeElements function so that instead of printing as a side-effect it returns a sequence of integers, where the sequence is empty if the range was not created. What I want to write is this.
def rangeElements(n: Int):Seq[(Range,Int)] = {
for {
r <- createRange(n)
x <- r
} yield (r, x)
}
// rangeElements(3) returns an empty sequence
// rangeElements(4) returns the sequence (Range(0,1,2,3), 0), (Range(0,1,2,3), 1) etc.
This gives me two type mismatch compiler errors. The r <- createRange(n) line required Seq[Int] but found scala.util.Try[Nothing]. The x <- r line required scala.util.Try[?] but found scala.collection.immutable.IndexedSeq[Int].
Presumably there is some type erasure with the Try that is messing me up, but I can't figure out what it is. I've tried various toOption and toSeq qualifiers on the lines in the for comprehension to no avail.
If I only needed to yield the range elements I could explicitly handle the Success and Failure conditions of createRange myself as suggested by the first two answers below. However, I need access to both the range and its individual elements.
I realize this is a strange-sounding example. The real problem I am trying to solve is a complicated recursive search, but I don't want to add in all its details because that would just confuse the issue here.
How do I write rangeElements to yield the desired sequences?
The problem becomes clear if you translate the for comprehension to its map/flatMap implementation (as described in the Scala Language Spec 6.19). The flatMap has the result type Try[U] but your function expects Seq[Int].
for {
r <- createRange(n)
x <- r
} yield x
createRange(n).flatMap {
case r => r.map {
case x => x
}
}
Is there any reason why you don't use the getOrElse method?
def rangeElements(n: Int):Seq[Int] =
createRange(n) getOrElse Seq.empty
The Try will be Success with a Range when n is even or a Failure with an Exception when n is odd. In rangeElements match and extract those values. Success will contain the valid Range and Failure will contain the Exception. Instead of returning the Exception return an empty Seq.
import scala.util.{Try, Success, Failure}
def createRange(n: Int): Try[Range] = {
Try {
if (n % 2 == 1) throw new Exception
else Range(0, n)
}
}
def rangeElements(n: Int):Seq[Tuple2[Range, Int]] = createRange(n) match {
case Success(s) => s.map(xs => (s, xs))
case Failure(f) => Seq()
}
scala> rangeElements(3)
res35: Seq[(Range, Int)] = List()
scala> rangeElements(4)
res36: Seq[(Range, Int)] = Vector((Range(0, 1, 2, 3),0), (Range(0, 1, 2, 3),1), (Range(0, 1, 2, 3),2), (Range(0, 1, 2,3),3))