Reputation: 1214
So I'm trying to recreate this code with Scala. This is what I have so far:
/*
This is a program for the #259 [Easy] Clarence the Slow Typist /r/dailyprogrammer challenge
The algorithm was created by /u/derision.
*/
object Clarence {
def main(args: Array[String]) {
val ip = args(0)
println(ip.tail.zip(ip).map(_.map(x => "123456789.0".indexOf(x))))
}
}
This should produce a 2d array, but when I run it I get the following error:
scala Clarence.scala 219.45.143.143
/home/mattjone/sw/coding/learning-scala/Clarence.scala:8: error: value productElements is not a member of (Char, Char)
println(ip.tail.zip(ip).map(_.map(x => "123456789.0".indexOf(x))))
^
one error found
From what I can tell it's saying that you can't use .map on a array of characters, but that doesn't make sense. How should I be doing this?
Upvotes: 1
Views: 172
Reputation: 89
Tzach Zohar answered you about why map
don't worked.
My codes may be not relate to that issue, but if you want to create 2D Char list in Scala, how about this solution?
val x = "123456789.0".toList.sliding(2).map(_.reverse).toList
This code will transform from "12345..." to List(List(2, 1), List(3, 2), List(4, 3)...) (List[List[Char]]
)
But if you want the list members to be Tuple2
, you can use this code instead:
val x = "123456789.0".toList.sliding(2).map(x => (x.last, x.head)).toList
and it will generate List((2,1), (3,2), (4,3), ...) (List[(Char, Char)]
).
Then you can just print it later :)
Upvotes: 0
Reputation: 37832
It says that map
is not a member of (Char, Char)
, which is a Tuple, not an array.
If you extract ip.tail.zip(ip)
into a var
, you can see it's type is Seq[(Char, Char)]
:
val zip: IndexedSeq[(Char, Char)] = ip.tail.zip(ip)
You can solve this by transforming each tuple into a sequence (with size 2), for example using productIterator
(but there are other ways):
println(ip.tail.zip(ip).map(_.productIterator.toList.map(x => "123456789.0".indexOf(x))))
That would result in printing a 2D "array" (actually a Vector
of List
s).
Perhaps a more readable version would be one that prints a list of Tuples, and names each part of the tuple for clarity:
// this will be applied to each part of the tuple:
def transformChar(c: Char): Int = "123456789.0".indexOf(c)
// map each tuple to a new transformed tuple:
println(ip.tail.zip(ip).map {
case (prev, cur) => (transformChar(prev), transformChar(cur))
})
Upvotes: 1