1

I'm working on creating a (simple) agent-based model to learn Scala and functional programming.

I already created it in Python, so my idea is to code it following the already existing ideas, but I ran into a problem just at the beginning:

I have a class which describes an agent in the model, and another class which describes the society it lives in. The society is composed of N agents, where N is an integer. In Python I would do a list-comprehension to store all the instances of the class, but how do I do this in Scala? Is there a better way than using the following code:

import agent.Agent

class Society([omitted-for-brevity]){

val tmp_agents = List()

for(i <- 1 to puntos){
    val tmp_agent = new Agent(pos_X = 0, name="Agent "+i)
    tmp_agents :+ tmp_agent
}
  • The Agent has values that can change, so the val tmp_agent in the for-loop shouldn't it be a var? Or is it valid if the Agent class has var arguments as inputs?
  • Should the tmp_agents list be a val if only the objects in it are going to change "internal" values? Is it OK to append to a val?
plr
  • 244
  • 1
  • 15

3 Answers3

6

As I always say, the Scaladoc is your friend.

val agents = List.tabulate(n) { i =>
  new Agent(pos_X = 0, name=s"Agent $i")
}

(also, I would recommend using a case class for your agents. And follow the Scala naming conventions)

3

You can do something similar with map in scala

val tmp_agents = (1 to puntos).toList.map(i -> new Agent(pos_X = 0, name="Agent "+i))

You can omit the .toList part if you don't care about the shape of your data and you just want a collection to hold your agents in

user
  • 7,435
  • 3
  • 14
  • 44
1
case class Agent(pos_X: Int, name: String)
val puntos = 20
(1 to puntos)
  .foldLeft(List.empty[Agent])((a, b) => Agent(b, s"Agent {b}") :: a)
  .reverse

The above one will help you model the program that you are trying to build. You can use foldLeft to build the same, and you can append it to the list and then reverse the list. You don't need any mutation or mutable data structure.

<script src="https://scastie.scala-lang.org/CeVBrWQhQmqCtwrXuimgcA.js"></script>
Shankar Shastri
  • 1,134
  • 11
  • 18