Skip to content

Instantly share code, notes, and snippets.

@MarkCLewis
Last active December 18, 2021 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkCLewis/8ad35e4fd0f5112d7aa17082a037dabf to your computer and use it in GitHub Desktop.
Save MarkCLewis/8ad35e4fd0f5112d7aa17082a037dabf to your computer and use it in GitHub Desktop.
Lambda Comparison (Python vs. Scala)
import random
def attack(numTimes, dieSides):
"""
Return a list of functions for attacks. Max roll takes 10% of health.
Other values do that much damage.
"""
damageFuncs = []
for i in range(1, numTimes):
d = random.randint(1, dieSides)
if d == dieSides:
damageFuncs.append(lambda hits: max(d, hits / 10))
else:
damageFuncs.append(lambda hits: d)
return damageFuncs
damage = attack(5, 6)
hp = 200
for d in damage:
hp -= d(hp)
print(hp)
/**
* Return a list of functions for attacks. Max roll takes 10% of health.
* Other values do that much damage.
*/
def attack(numTimes: Int, dieSides: Int): List[Int => Int] =
var damageFuncs = List[Int => Int]()
for i <- 1 to numTimes do
val d = util.Random.between(1, dieSides + 1)
if d == dieSides then
damageFuncs = damageFuncs.appended((hits: Int) => math.max(d, hits / 10))
else
damageFuncs = damageFuncs.appended((hits: Int) => d)
damageFuncs
@main def start =
val damage = attack(5, 6)
var hp = 200
for d <- damage do
hp -= d(hp)
println(hp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment