DEV Community

Discussion on: Daily Coding Puzzles - Nov 11th - Nov 16th

Collapse
 
kungtotte profile image
Thomas Landin

My solution in Nim, my new favourite language :)

It provides an automatic default return variable called "result" that you can just start stuffing things into and it will automatically return it without you doing anything :)

let
  rate = 40.0
  weekly_discount = 50.0
  weekend_discount = 20.0
  test_data = [1, 2, 3, 4, 5, 6, 7, 8, 9]

proc total_cost(days: int): float =
  result = days.float * rate
  if days >= 7:
    result -= weekly_discount
  elif days >= 3:
    result -= weekend_discount

for n in test_data:
  echo "Cost for ", n, " days is: ", total_cost(n)
Collapse
 
jay profile image
Jay

I try to use the func keyword when defining methods, that way the compiler can guarantee that I have pure function with no side effects.
func is just sugar for proc {.noSideEffect.}.

func rental_car_cost(days: int): int =
  result = days * 40
  if days > 7:
    result -= 50
  elif days >= 3:
    result -= 20
Thread Thread
 
kungtotte profile image
Thomas Landin

I haven't gotten into the habit of doing that yet. I know I should and I think it's a great idea in general, but years of habits are hard to break and the func keyword is still a fairly recent addition to the language :)