HW4 Review Case Classes.

Slides:



Advertisements
Similar presentations
7-Jun-14 Lists. Arrays and Lists Arrays are a fixed length and occupy sequential locations in memory This makes random access (for example, getting the.
Advertisements

Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists A list is a finite sequence of elements. [3,5,9] ["a", "list" ] [] Elements may appear more than once [3,4]
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Introduction to OCaml Slides prepared by Matt Gruskin Some material borrowed from the CIS 500 lecture notes.
F28PL1 Programming Languages Lecture 14: Standard ML 4.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
Def f(n): if (n == 0): return else: print(“*”) return f(n-1) f(3)
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
Java Review Interface, Casting, Generics, Iterator.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Map and Fold Building Powerful Abstractions. Hello. I’m Zach, one of Sorin’s students.
Week 5 - Associative Containers: sets and maps. 2 2 Main Index Main Index Content s Content s Container Types Sequence Containers Adapter Containers Associative.
Defining functions in lisp In lisp, all programming is in terms of functions A function is something which –takes some arguments as input –does some computing.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Java Coding Standards and Best Practices Coding Standards Introduction: After completing this chapter, you will able to keep your code up to standards.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Logistics, Exercises and Demos Everyone should register for the course ‘SAV’ in whatAFunCourse Please obtain “The Calculus of Computation”
And other languages….  Array literals/initialization a = [1,2,3] a2 = [-10..0, 0..10] a3 = [[1,2],[3,4]] a4 = [w*h, w, h] a5 = [] empty = Array.new zeros.
F28PL1 Programming Languages Lecture 13: Standard ML 3.
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
CSED101 INTRODUCTION TO COMPUTING SUM TYPE 유환조 Hwanjo Yu.
2014-T2 Lecture 27 School of Engineering and Computer Science, Victoria University of Wellington  Lindsay Groves, Marcus Frean, Peter Andreae, and Thomas.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
Getting Functional. Object-Oriented Programming in Scala Scala is object-oriented, and is based on Java’s model An object is a singleton object (there.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
Scala HW5 Part 2 Combine Until Encode Decode. Combine Not sure what a correct test case is Fork(Leaf('d',4),Fork(Leaf('a',2),Leaf('b',3),List('a ', 'b'),5),List('d',
Functional Processing of Collections (Advanced) 6.0.
UMBC CMSC 331 Case Classes in Scala Intro. Basic Properties Case classes are regular classes which export their constructor parameters and which provide.
Principles of programming languages 12: Functional programming
ML: a quasi-functional language with strong typing
Assignment 4 Kang-Pil Kim, Jin Kim
CS-104 Final Exam Review Victor Norman.
ML Again ( Chapter 7) Patterns Local variable definitions
From Think Python How to Think Like a Computer Scientist
Lambdas ---anonymous functions---
Getting Functional.
2.0 FUNDAMENTALS OF JAVA PROGRAMMING LANGUAGE
PROGRAMMING IN HASKELL
Feedback from Assignment 1
Haskell Strings and Tuples
null, true, and false are also reserved.
Selection CSCE 121 J. Michael Moore.
CMSC 202 Templates.
Nicholas Shahan Spring 2016
Passing Parameters by value
תירגול 9 אובייקטים.
Ruth Anderson UW CSE 160 Winter 2017
Recap Week 2 and 3.
topics mutable data structures
(more) Python.
6.001 SICP Interpretation Parts of an interpreter
Scala Apologia 27-Apr-19.
Ruth Anderson UW CSE 160 Spring 2018
6.2 Using Substitution to Solve Systems
Lecture 20 – Practice Exercises 4
Recap from year 8: How many different factorised forms can you find?
Lecture 2 – Abstract Data Type (ADT)
Review Previously in: Lots of language features: functions, lists, records, tuples, variants, pattern matching Today: No new language features New idioms.
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

HW4 Review Case Classes

Case Classes Why? Immutable classes with ctor parameters. Easier than defining setters and getters and a class for them. Reduces Boilerplate from J2EE EJBshttps://gist.github.com/dougc333/2975185224510197e005 How to move the common weight into abstract class?

Case Class For weight move into ABC abstract class CodeTree2 { val name:String def weight:Int } case class Fork3(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree case class Leaf3(char: Char, weight: Int) extends CodeTree object foo2 extends Application{ val l3 = Leaf3('a',1) println(l3.weight) val f3 = Fork3(l3, Leaf3('b',2),List('c'),4) println(f3.weight) 1 4 For weight move into ABC def weight(tree: CodeTree): Int = { tree.weight

Case classes Autoimplement getters/setters & no instanceof needed. Return ivars from ctor args def chars(tree: CodeTree): List[Char] = tree match{ case Fork(_, _, chars, _) => chars case Leaf(char, _) => List(char) }

MakeCodeTree Fork is for combining 2 CodeTrees, to add lists together use ++ or :::. def makeCodeTree(left: CodeTree, right: CodeTree) = Fork(left, right, chars(left) ++ chars(right), weight(left) + weight(right))

times def times(chars: List[Char]): List[(Char, Int)] = { def timesAcc(chars:List[Char],acc:Map[Char,(Char,Int)]):Map[Char,(Char,Int)] = chars match { case Nil => acc case x::xs => if (acc contains x) {val tmpacc=acc.updated(x,(x,acc(x)._2+1));timesAcc(xs,tmpacc)} else {val tmpacc=acc+(x->(x,1));timesAcc(xs,tmpacc)}; } timesAcc(chars,Map()).values.toList This is a good time to practice. Reduce number of new things to learn. Remove pairs, remove return Implement def times(chars:List[Chars]) and put in print statements to show what is happening

Iterating through list //iterate through the list def testMe2(chars:List[Char]):Unit={ def testMe2Acc(chars:List[Char]) = chars match{ case Nil => println("testMe2 match empty list") case x::xs => println("testMe2 not empty List x:"+x+",xs:"+xs); testMe2(xs) } testMe2Acc(chars) Write test code to verify your print statements match what is happening and you can iterate through the list.

Add accumulator def testMe3(chars:List[Char]):Unit={ def testMe3Acc(chars:List[Char],acc:Map[Char,Int]):Unit = chars match{ case Nil => println("testMe3 match empty list") case x::xs => println("testMe3 not empty List x:"+x+",xs:"+xs);println("acc:"+acc); if (acc contains x) {val tmpacc=acc.updated(x,acc(x)+1);println("contains acc after add+"+tmpacc);testMe3Acc(xs,tmpacc)} else {println("not contains adding");val tmpacc=acc+(x->1);print("acc after add:"+tmpacc);testMe3Acc(xs,tmpacc)}; } testMe3Acc(chars,Map())

Add Pairs w/no return type //make pairs, w/o return type def testMe5(chars:List[Char]):Unit={ def testMe5Acc(chars:List[Char],acc:Map[Char,(Char,Int)]):Unit = chars match{ case Nil => println("testMe5 empty list"); case x::xs => println("testMe5 char:"+x);println("acc before insert:"+acc); if (acc contains x) {val tmpacc=acc.updated(x,(x,acc(x)._2+1));println("tmpacc+"+tmpacc);testMe5Acc(xs,tmpacc)} else {println("not contains adding");val tmpacc=acc+(x->(x,1));print("acc after add:"+tmpacc);testMe5Acc(xs,tmpacc)}; } testMe5Acc(chars,Map())

Add map return and convert to list def testMe6(chars:List[Char]):List[(Char,Int)]={ def testMe6Acc(chars:List[Char],acc:Map[Char,(Char,Int)]):Map[Char,(Char,Int)] = chars match{ case Nil => println("testMe6 empty list");acc case x::xs => println("testMe6 char:"+x);println("acc before insert:"+acc); if (acc contains x) {val tmpacc=acc.updated(x,(x,acc(x)._2+1));println("tmpacc+"+tmpacc);testMe6Acc(xs,tmpacc)} else {println("not contains adding");val tmpacc=acc+(x->(x,1));print("acc after add:"+tmpacc);testMe6Acc(xs,tmpacc)}; } testMe6Acc(chars,Map()).values.toList

Final answer for times def times(chars: List[Char]): List[(Char, Int)] = { def timesAcc(chars:List[Char],acc:Map[Char,(Char,Int)]):Map[Char,(Char,Int)] = chars match { case Nil => acc case x::xs => if (acc contains x) {val tmpacc=acc.updated(x,(x,acc(x)._2+1));timesAcc(xs,tmpacc)} else {val tmpacc=acc+(x->(x,1));timesAcc(xs,tmpacc)}; } timesAcc(chars,Map()).values.toList

Sort list then convert Pairs to leaf def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = { freqs.sortBy(Tuple2 => Tuple2._2).map(Tuple2 => Leaf(Tuple2._1, Tuple2._2)) }

Singleton def singleton(trees:List[CodeTree]):Boolean ={ if (trees.length == 1) true false }

Combine, 2 examples Tree match & no tree match def combine(trees: List[CodeTree]): List[CodeTree] = trees match{ case first::second::restofList => { val ct = makeCodeTree(first,second) val large = trees.filter(x=>weight(x)>weight(ct)) return ct::large } case _ => println("less than 2"); trees //if less than 2 return trees def combine2(trees: List[CodeTree]): List[CodeTree] = { if (trees.length>=2) { val ct = makeCodeTree(trees.head,trees(2)) trees