Reputation: 5903
Scala is new to me so I'm not sure the best way to go about this.
I need to simply take the strings within a single list and join them.
So, concat(List("a","b","c"))
returns abc
.
Should I first see how many strings there are in the list, that way I can just loop through and join them all? I feel like that needs to be done first, that way you can use the lists just like an array and do list[1]
append list[2]
append list[3]
, etc..
Edit:
Here's my idea, of course with compile errors..
def concat(l: List[String]): String = {
var len = l.length
var i = 0
while (i < len) {
val result = result :: l(i) + " "
}
result
}
Upvotes: 15
Views: 27684
Reputation: 17980
A bit longer that mkString but more efficient:
s.foldLeft(new StringBuilder())(_ append _).toString()
Upvotes: 0
Reputation:
How about this, on REPL
List("a","b","c") mkString("")
or in script file
List("a","b","c").mkString("")
Upvotes: 37
Reputation: 37435
Some options to explore for you:
Given the basic level of the problem, I think you're looking at learning some fundamentals in programming. If the language of choice is Scala, probably the focus is on functional programming, so I'd put effort on solving #2, then solve #1. #3 for extra credits.
Upvotes: 2
Reputation: 16859
I'm just assuming here that you are not only new to Scala, but also new to programming in general. I'm not saying SO is not made for newbies, but I'm sure there are many other places, which are better suited for your needs. For example books...
I'm also assuming that your problem doesn't have to be solved in a functional, imperative or some other way. It just has to be solved as a homework assignment.
So here are the list of things you should consider / ask yourself:
Upvotes: -1
Reputation: 54574
In functional programming, fold ... is a family of higher-order functions that iterate an arbitrary function over a data structure in some order and build up a return value.
http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29
That sounds like something you could use.
As string concatenation is associative (to be exact, it forms a monoid having the empty String as neutral element), the "direction" of the fold doesn't matter (at least if you're not bothered by performance).
Speaking of performance: In real life, it would be a good idea to use a StringBuilder
for the intermediate steps, but it's up to you if you want to use it.
Upvotes: 0
Reputation: 9397
This exercise is designed to encourage you to think about the problem from a functional perspective. You have a set of data over which you wish to move, performing a set of identical operations. You've already identified the imperative, looping construct (for
). Simple enough. Now, how would you build that into a functional construct, not relying on "stateful" looping?
Upvotes: 1