Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
fp:lab02 [2021/03/25 14:38]
pdmatei
fp:lab02 [2023/03/10 10:16] (current)
pdmatei
Line 1: Line 1:
-====== 2. Introduction to Haskell ​======+====== 2. Scala syntax and function definition ​======
  
 +** Objectives: **
 +  * get yourself familiar with Scala syntax basics
 +  * practice writing **tail-recursive** functions as an alternative to imperative **loops** ​
 +  * keep your code clean and well-structured.
  
-===== 2.1. Functions in Haskell =====+** Create a new Scala worksheet to write your solutions **
  
-In mathematics,​ functions have a domain an codomain. In Haskell, functions have **types** or **signatures**. They often can be omitted in Haskell, but can 
-also be explicitly written as in: 
  
-<code haskell>​ +**2.1.** Write a tail-recursive function that computes the factorial of a natural number. Start from the code stub below:
-:: Integer -> Integer -> Integer +
-f x y = x + y +
-</​code>​+
  
-or: +<​code ​scala
-<​code ​haskell+def fact (nInt)Int { 
-:: Bool -> Bool +   def aux_fact(i: Int, acc: Int): Int  
-f True False +       if (???) acc 
-f False True+       else ??? 
 +   ??? 
 +}
 </​code>​ </​code>​
  
-The previous example illustrates ​that we can define functions by specifying ​behaviour for given values.+**2.2.** Implement a tail-recursive function ​that computes the greatest common divisor of natural number:
  
-2.1.1. Write a function together with its signature, which implements boolean AND: +<​code ​scala
-<​code ​haskell+def gcd(aInt, bInt): Int = ???
-myand :: Bool -> Bool -> Bool +
-...+
 </​code>​ </​code>​
  
-===== 2.2. If and conditionals (guards) ===== +**2.3.** Write a tail-recursive ​function takes an integer ​$math[n] and computes ​the value $math[1 + 2^2 + 3^2 + ... + (n-1)^2 + n^2]. (Hint: use inner functions).
-2.2.1. Write an implementation for a function ​''​ifp''​ which takes a boolean, expressions ​$math[e_1] and $math[e_2] and returns $math[e_1] if the boolean is true and $math[e_2] otherwise. +
-<code haskell>​ +
-ifp = ... +
-</​code>​+
  
-2.2.2. Write a function which takes three integers and returns the largest. Hint - sometimes parentheses are **important in function calls**. +<​code ​scala
-<​code ​haskell+def sumSquares(nInt)Int = ???
-:: Integer -> Integer -> Integer -> Integer+
 </​code>​ </​code>​
  
-In Haskell, we can use the if construct, in a manner almost identical to the above implementation,​ e.g. +===== Newton'​s Square Root method =====
-<code haskell>​ +
-f x if x == 0 then 1 else 0 +
-</​code>​+
  
-The previous function returns ​if x is equal to 0 and 0 otherwiseA more elegant way is to use **guards**+A very fast way to numerically compute $math[\sqrt{a}],​ often used as a standard //sqrt(.)// implementation,​ relies on Newton'​s Square Root approximation. ​The main idea relies on starting with an estimate (often ​1), and incrementally improving the estimateMore precisely
-<code haskell>​ +  * Start with $math[x_0 ​= 1]. 
-f x +  * Compute $math[x_{n+1} ​\displaystyle\frac{1}{2}(x_n+\frac{a}{x_n})]
-   | x == 0 = 1 +
-   | otherwise ​+
-</​code>​+
  
-More generally, guards can be used as follows: +**2.4.** Implement the function ''​improve''​ which takes an estimate $math[x_n] of $math[\sqrt{a}] and improves it (computes $math[x_{n+1}]). 
-<​code ​haskell+<​code ​scala
-<​function_name>​ <​parameters>​ +def improve(xn: Double, a: Double): Double ​???
-  | <​boolean_condition_1> ​<​expression_1>​ +
-  | <​boolean_condition_2>​ = <​expression_2>​ +
-  ... +
-  | otherwise = <​expression_n>​+
 </​code>​ </​code>​
  
-2.2.3. Solve the previous exercise using guards. +**2.5.** Implement ​the function ''​nthGuess''​ which starts with $math[x_0 ​1] and computes ​the nth estimate $math[x_n] ​of $math[\sqrt{a}]
- +<​code ​scala
-===== 2.3. Lists ===== +def nth_guess(n:​ Int, a: Double): Double ​???
- +
-The following code examples illustrate ​the usage of lists+
-<​code ​haskell+
--- defining a new list +
-l = [1,2,3] +
- +
--- adds x to the beginning of list l. The operator ​is called '​cons'​ and it is infix (just like +) +
-cons x l = x:+
- +
--- the previous list can be defined also as: +
-lp = 1:2:3:[] +
- +
--- function head returns the first element of a list  +
-first_of_l = head l +
- +
--- function tail removes the first element of a list and returns the result +
-remove_first_of_l = tail l +
- +
--- the infix operator ++ concatenates lists. +
-lpp l ++ lp+
 </​code>​ </​code>​
  
-2.3.1Implement reversal +Note that: 
- +  * for smaller $math[a], there is no need to compute $math[n] estimations as $math[(x_n)_n] converges quite fast to $math[\sqrt{a}].  
-2.3.2. Write a function which extracts the third to last integer from a list and returns ''​True''​, if that number is odd (hint: the function ''​mod'' ​may be useful), and false otherwise. If the list has fewer than three elements, the function should also return false+  
-<​code>​ +**2.6.** Thus, implement the function ​''​acceptable'' ​which returns ''​true'' ​iff $math[\mid x_n^2 - a \mid \leq 0.001]. ​(Hint, google ​the ''​abs'' ​function ​in Scala. Don't forget to import ​''​scala.math._''​). 
-            V +<​code ​scala
-   f [3,4,5,2,3,9] = False +  def acceptable(xn:​ Doublea: Double): Boolean ​???
-   f [3,​4,​2,​1,​4,​4] ​True+
 </​code>​ </​code>​
  
-Using ''​head'' ​and ''​tail'' ​can become tedious if we need to extract specific inner elements of a listAlternatively,​ we can use **list patterns** in function definition, in order to explore ​the structure ​of a list. A few examples are given below. +**2.7.** Implement the function ​''​mySqrt'' ​which computes the square root of an integer ​''​a''​. ​Modify the previous implementations ​to fit the following code structure: 
- +<​code ​scala
-<​code ​haskell+def mySqrt(a: Double): Double = { 
--- this function uses patterns to test if list is empty. The pattern 'x:xs' refers to a list where the first element is x and the rest of the list is xs +   def improve(xn: Double): Double ​??? 
-is_empty [] True +   def acceptable(xnDouble): Boolean ​??? 
-is_empty ​(x:xs) = False+    
 +   def tailSqrt(estimate:​ Double): Double = ??? 
 +    
 +   ??? 
 +}
 </​code>​ </​code>​
  
-2.3.3. Implement the previous exercise using patterns +**2.8(!) **  ​Try ​out your code for: ''​2.0e50'' ​(which is $math[2.0\cdot 10^{50}]) or ''​2.0e-50''​. ​The code will likely take very long time to finish. The reason is that $math[xn^a] will suffer from rounding error which may be larger than 0.001Can you find different implementation for the function ''​acceptable''​ which takes that into account? (Hint: the code is just as simple as the original one)
- +
-2.3.4. Implement a function which returns the sum of integers from a list. +
- +
-2.3.5. Implement a function which takes a list of booleans and returns false if **at least** one boolean from the list is false. +
- +
-2.3.6. Implement a function which filters ​out all odd numbers from a list. +
- +
-2.3.7. Implement a function which takes a list of booleans and returns a list of integers. In the latter, (''​True''​ becomes ''​1''​ and ''​False''​ becomes ''​0''​)Example: ​''​f [False, True, False] = [0,1,0]''​+
- +
-We can construct more complicated patterns from simpler ones: +
-<code haskell>​ +
--- this function returns true if the list given as parameter has at least tree elements. +
-f (x:y:z:xs) = True +
-f _ = False +
-</​code>​ +
- +
-===== 2.4. Strings ===== +
- +
-The following example illustrates the usage of ''​Char''​ and ''​String''​. In Haskell, ''​String''​ is a type-alias for ''​[Char]''​ (strings are lists of chars and can be introspected using pattern matching as well). +
- +
-<code haskell>​ +
--- this function returns true if the parameter is the character 'a+
-f '​a'​ = True +
-f _ = False +
- +
--- this function returns true if the given string has the SECOND character equal to '​b'​ and false otherwise (or if the string has less than two characters) +
-g (_:'​b':​xs) = True +
-g _ = False +
-</​code>​ +
- +
-2.4.1. Write function ​which removes all empty strings from a list. +
- +
-2.4.2Write function which removes all strings of size smaller than 3. Do **not** use the builtin ​function ''​length''​+
- +
-2.4.3. Write a function which removes all strings having the third letter equal to '​a'​. +
- +
-2.4.4. Write a function ​which: +
-    * removes all strings which are not **names**. A **name** always starts with an uppercase. +
-    * removes ​the last name from the resulting list of names. A name always comprises of the first name followed by the last name. +
- +