Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8582523
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T21:18:45+00:00 2026-06-11T21:18:45+00:00

I have the following Scala snippet. In order to solve my given problem, I

  • 0

I have the following Scala snippet. In order to solve my given problem, I “cheat” a little and use a var — essentially a non-final, mutable data type. Its value is updated at each iteration through the loop. I’ve spent quite a bit of time trying to figure out how to do this using only recursion, and immutable data types and lists.

Original snippet:

  def countChange_sort(money: Int, coins: List[Int]): Int =
    if (coins.isEmpty || money < 0)
      0
    else if (coins.tail.isEmpty && money % coins.head != 0) {
      0
    } else if (coins.tail.isEmpty && money % coins.head == 0 || money == 0) {
      1
    } else {
      -- redacted --
    }
}

Essentially, are there any basic techniques I can use to eliminate the i and especially the accumulating cnt variables?

Thanks!!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T21:18:46+00:00Added an answer on June 11, 2026 at 9:18 pm

    There are lots of different ways to solve problems in functional style. Often you start by analysing the problem in a different way than you would when designing an imperative algorithm, so writing an imperative algorithm and then “converting” it to a functional one doesn’t produce very natural functional algorithms (and you often miss out on lots of the potential benefits of functional style). But when you’re an experienced imperative programmer just starting out with functional programming, that’s all you’ve got, and it is a good way to begin getting your head around the new concepts. So here’s how you can approach “converting” such a function as the one you wrote to functional style in a fairly uncreative way (i.e. not coming up with a different algorithm).

    Lets just consider the else expression since the rest is fine.

    Functional style has no loops, so if you need run a block of code a number of times (the body of the imperative loop), that block of code must be a function. Often the function is a simple non-recursive one, and you call a higher-order function such as map or fold to do the actual recursion, but I’m going to presume you need the practice thinking recursively and want to see it explicitly. The loop condition is calculated from the quantities you have at hand in the loop body, so we just have the loop-replacement function recursively invoke itself depending on exactly the same condition:

    } else {
      var cnt = 0
      var i = 0
    
      def loop(????) : ??? = {
        if (money - (i * coins.head) > 0) {
          cnt += countChange_sort(money - (i * coins.head), coins.tail)
          i = i + 1
          loop(????)
        }
      }
    
      loop(????)
      cnt
    }
    

    Information is only communicated to a function through its input arguments or through its definition, and communicated from a function through its return value.

    The information that enters a function through its definition is constant when the function is created (either at compile time, or at runtime when the closure is created). Doesn’t sound very useful for the information contained in cnt and i, which needs to be different on each call. So they obviously need to be passed in as arguments:

    } else {
      var cnt = 0
      var i = 0
    
      def loop(cnt : Int, i : Int) : ??? = {
        if (money - (i * coins.head) > 0) {
          cnt += countChange_sort(money - (i * coins.head), coins.tail)
          i = i + 1
          loop(cnt, i)
        }
      }
    
      loop(cnt, i)
    
      cnt
    }
    

    But we want to use the final value of cnt after the function call. If information is only communicated from loop through its return value, then we can only get the last value of cnt by having loop return it. That’s pretty easy:

    } else {
      var cnt = 0
      var i = 0
    
      def loop(cnt : Int, i : Int) : Int = {
        if (money - (i * coins.head) > 0) {
          cnt += countChange_sort(money - (i * coins.head), coins.tail)
          i = i + 1
          loop(cnt, i)
        } else {
          cnt
        }
      }
    
      cnt = loop(cnt, i)
    
      cnt
    }
    

    coins, money, and countChange_sort are examples of information “entering a function through its definition”. coins and money are even “variable”, but they’re constant at the point when loop is defined. If you wanted to move loop out of the body of countChange_sort to become a stand-alone function, you would have to make coins and money additional arguments; they would be passed in from the top-level call in countChange_sort, and then passed down unmodified in each recursive call inside loop. That would still make loop dependent on countChange_sort itself though (as well as the arithmetic operators * and -!), so you never really get away from having the function know about external things that don’t come into it through its arguments.

    Looking pretty good. But we’re still using assignment statements inside loop, which isn’t right. However all we do is assign new values to cnt and i and then pass them to a recursive invocation of loop, so those assignments can be easily removed:

    } else {
      var cnt = 0
      var i = 0
    
      def loop(cnt : Int, i : Int) : Int = {
        if (money - (i * coins.head) > 0) {
          loop(cnt + countChange_sort(money - (i * coins.head), coins.tail), i + 1)
        } else {
          cnt
        }
      }
    
      cnt = loop(cnt, i)
    
      cnt
    }
    

    Now there are some obvious simplifications, because we’re not really doing anything at all with the mutable cnt and i other than initialising them, and then passing their initial value, assigning to cnt once and then immediately returning it. So we can (finally) get rid of the mutable cnt and i entirely:

    } else {
      def loop(cnt : Int, i : Int) : Int = {
        if (money - (i * coins.head) > 0) {
          loop(cnt + countChange_sort(money - (i * coins.head), coins.tail), i + 1)
        } else {
          cnt
        }
      }
    
      loop(0, 0)
    }
    

    And we’re done! No side effects in sight!

    Note that I haven’t thought much at all about what your algorithm actually does (I have made no attempt to even figure out whether it’s actually correct, though I presume it is). All I’ve done is straightforwardly applied the general principle that information only enters a function through its arguments and leaves through its return values; all mutable state accessible to an expression is really extra hidden inputs and hidden outputs of the expression. Making them immutable explicit inputs and outputs, and then allows you to prune away unneeded ones. For example, i doesn’t need to be included in the return value from loop because it’s not actually needed by anything, so the conversion to functional style has made it clear that it’s purely internal to loop, whereas you had to actually read the code of the imperative version to deduce this.

    cnt and i are what is known as accumulators. Accumulators aren’t anything special, they’re just ordinary arguments; the term only refers to how they are used. Basically, if your algorithm needs to keep track of some data as it goes, you can introduce an accumulator parameter so that each recursive call can “pass forward” the data from what has been done so far. They often fill the role that local temporary mutable variables fill in imperative algorithms.

    It’s quite a common pattern for the return value of a recursive function to be the value of an accumulator parameter once it is determined that there’s no more work left to do, as happens with cnt in this case.

    Note that these sort of techniques don’t necessarily produce good functional code, but it’s very easy to convert functions implemented using “local” mutable state to functional style using this technique. Pervasive non-local use of mutability, such as is typical of most traditional OO programs, is harder to convert like this; you can do it, but you tend to have to modify the entire program at once, and the resulting functions have large numbers of extra arguments (explicitly exposing all the hidden data-flow that was present in original program).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In trying to use Scala with JPA, I have the following snippet as part
I have the following Scala code: class X[T1 <: AnyRef] { var _x :
I have the following problem in scala. I have to find the first element
I have this rather simple question about Scala. Given that i have to following
I have the following map in Scala: var m = Map[Int,Set[Int]]() m += 1
Suppose I have a the following in Scala object Foo { var functions: List[String
I have the following class definition in Scala: class AppendErrorMessageCommand private(var m_type: Byte) {
I have the following pattern matching case in a scala function: def someFunction(sequences: Iterable[Seq[Int]]):Seq[Int]
In Scala IDE I have the following code: package pkg.one object S { class
Disclaimer: absolute novice in Scala :( I have the following defined: def tryAndReport(body: Unit)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.