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 7630563
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T06:08:10+00:00 2026-05-31T06:08:10+00:00

For a homework assignment I wrote some scala code in which I have the

  • 0

For a homework assignment I wrote some scala code in which I have the following classes and object (used for modeling a binary tree):

object Tree {
  def fold[B](t: Tree, e: B, n: (Int, B, B) => B): B = t match {
    case Node(value, l, r) => n(value,fold(l,e,n),fold(r,e,n))
    case _ => e
  }
  def sumTree(t: Tree): Tree = 
    fold(t, Nil(), (a, b: Tree, c: Tree) => {
      val left = b match {
        case Node(value, _, _) => value
        case _ => 0
      }
      val right = c match {
        case Node(value, _, _) => value
        case _ => 0
      }
      Node(a+left+right,b,c)
    })
}

abstract case class Tree
case class Node(value: Int, left: Tree, right: Tree) extends Tree
case class Nil extends Tree

My question is about the sumTree function which creates a new tree where the nodes have values equal to the sum of the values of its children plus it’s own value.

I find it rather ugly looking and I wonder if there is a better way to do this. If I use recursion which works top-down this would be easier, but I could not come up with such a function.

I have to implement the fold function, with a signature as in the code, to calculate sumTree

I got the feeling this can be implemented in a better way, maybe you have suggestions?

  • 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-05-31T06:08:11+00:00Added an answer on May 31, 2026 at 6:08 am

    First of all, I believe and if I may say so, you’ve done a very good job. I can suggest a couple of slight changes to your code:

    abstract class Tree 
    case class Node(value: Int, left: Tree, right: Tree) extends Tree
    case object Nil extends Tree
    
    1. Tree doesn’t need to be a case-class, besides using a case-class as non-leaf node is deprecated because of possible erroneous behaviour of automatically generated methods.
    2. Nil is a singleton and best defined as a case-object instead of case-class.
    3. Additionally consider qualifying super class Tree with sealed. sealed tells compiler that the class can only be inherited from within the same source file. This lets compiler emit warnings whenever a following match expression is not exhaustive – in other words doesn’t include all possible cases.

      sealed abstract class Tree

    The next couple of improvement could be made to the sumTree:

    def sumTree(t: Tree) = {
      // create a helper function to extract Tree value
      val nodeValue: Tree=>Int = {
        case Node(v,_,_) => v
        case _ => 0
      }
      // parametrise fold with Tree to aid type inference further down the line
      fold[Tree](t,Nil,(acc,l,r)=>Node(acc + nodeValue(l) + nodeValue(r) ,l,r)) 
    }
    

    nodeValue helper function can also be defined as (the alternative notation I used above is possible because a sequence of cases in curly braces is treated as a function literal):

    def nodeValue (t:Tree) = t match {
      case Node(v,_,_) => v
      case _ => 0
    }
    

    Next little improvement is parametrising fold method with Tree (fold[Tree]). Because Scala type inferer works through the expression sequentially left-to-right telling it early that we’re going to deal with Tree’s lets us omit type information when defining function literal which is passed to fold further on.

    So here is the full code including suggestions:

    sealed abstract class Tree
    case class Node(value: Int, left: Tree, right: Tree) extends Tree
    case object Nil extends Tree
    
    object Tree {
      def fold[B](t: Tree, e: B, n: (Int, B, B) => B): B = t match {
        case Node(value, l, r) => n(value,fold(l,e,n),fold(r,e,n))
        case _ => e
      }
      def sumTree(t: Tree) = {
        val nodeValue: Tree=>Int = {
          case Node(v,_,_) => v
          case _ => 0
        }
        fold[Tree](t,Nil,(acc,l,r)=>Node(acc + nodeValue(l) + nodeValue(r) ,l,r)) 
      }
    }
    

    The recursion you came up with is the only possible direction that lets you traverse the tree and produce a modified copy of the immutable data structure. Any leaf nodes have to be created first before being added to the root, because individual nodes of the tree are immutable and all objects necessary to construct a node have to be known before the construction: leaf nodes need to be created before you can create root node.

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

Sidebar

Related Questions

I have a homework assignment to write a multi-threaded sudoku solver, which finds all
I have to modify a simple shell I wrote for a previous homework assignment
I have a homework assignment where I need to take input from a file
I'm doing a basic homework assignment which looks like this: While input <> -1
Wrote up a basic file handler for a Java Homework assignment, and when I
This is for a homework assignment, so I don't want the exact code, but
I have a great idea for a homework note pad and I wrote the
I have done a homework assignment, here is the problem statement: Your program should
I'm working on a homework assignment translating a C program we wrote to MIPS.
For a homework assignment, I have to write a MySQL query to calculate the

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.