Differences
This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision | ||
|
pp:2026:scala:l05 [2026/03/26 07:56] ldaniel acum merge sa definesti + si * si in worksheet |
pp:2026:scala:l05 [2026/05/02 21:34] (current) cosmin.asavoae |
||
|---|---|---|---|
| Line 31: | Line 31: | ||
| <hidden Automatic conversions> | <hidden Automatic conversions> | ||
| <code scala> | <code scala> | ||
| - | given nat2Int: Conversion[Nat, Int] with | + | given nat2Int: Conversion[Nat, Int] = toInt |
| - | def apply(x: Nat): Int = toInt(x) | + | |
| - | given int2Nat: Conversion[Int, Nat] with | + | given int2Nat: Conversion[Int, Nat] = toNat |
| - | def apply(x: Int): Nat = toNat(x) | + | |
| // the second conversion is used to cast params from Int to Nat | // the second conversion is used to cast params from Int to Nat | ||
| Line 118: | Line 116: | ||
| </code> | </code> | ||
| - | **5.3.2** Write a function which takes a BinaryTree and returns the number of nodes in its subtree. | + | **5.3.2** Write a function which takes a BinaryTree and returns the total number of nodes in it. |
| <code scala> | <code scala> | ||
| - | def subtree(tree: BinaryTree): Int = ??? | + | def size(tree: BinaryTree): Int = ??? |
| </code> | </code> | ||
| Line 133: | Line 131: | ||
| </code> | </code> | ||
| - | **(!) 5.3.5** Write a function which takes two BinaryTree and tries to assign the second tree as a child of the first. It should return a "container" of a BinaryTree . | + | **(!) 5.3.5** Write a function which takes two BinaryTree and tries to assign the second tree as a child of the first. It should return a "container" of a BinaryTree. The append is successful if the second tree can become a direct child of the first tree's root. |
| <code scala> | <code scala> | ||
| def append(tree1: BinaryTree, tree2: BinaryTree): Option[BinaryTree] = ??? | def append(tree1: BinaryTree, tree2: BinaryTree): Option[BinaryTree] = ??? | ||
| Line 191: | Line 189: | ||
| will be represented by the list ''[ [1,2,3],[4,5,6],[7,8,9] ]''. | will be represented by the list ''[ [1,2,3],[4,5,6],[7,8,9] ]''. | ||
| + | <hidden Scala definition> | ||
| + | In Scala, we can define this matrix like this: | ||
| + | <code scala> | ||
| + | val mat = List(List(1, 2, 3), List(4, 5, 6), List(7,8,9)) | ||
| + | </code> | ||
| + | Or.. if you like Cons and Nil, like this: | ||
| + | <code scala> | ||
| + | val mat2 = (1::2::3::Nil)::(4::5::6::Nil)::(7::8::9::Nil)::Nil | ||
| + | </code> | ||
| + | </hidden> | ||
| To make signatures more legible, add the //type alias// to your code: | To make signatures more legible, add the //type alias// to your code: | ||
| <code scala> type Matrix = List[List[Int]] </code> | <code scala> type Matrix = List[List[Int]] </code> | ||