Differences
This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision | |||
| fp2023:lab08 [2023/04/25 16:29] pdmatei | fp2023:lab08 [2023/04/26 10:38] (current) pdmatei | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| ====== Lab 08: Polymorphism ======= | ====== Lab 08: Polymorphism ======= | ||
| - | ===== 8.1. Ad-hoc polymorphism ===== | + | ===== 8.1. Companion objects and Option ===== | 
| Consider the following implementation of the type ''Nat'', which you are well-familiar with: | Consider the following implementation of the type ''Nat'', which you are well-familiar with: | ||
| Line 32: | Line 32: | ||
| which can be called simply as: ''Nat(5)''. Also, we can ** (2) overload** ''apply'' in order to support creating naturals with the call ''Nat(.)'' from different other types. | which can be called simply as: ''Nat(5)''. Also, we can ** (2) overload** ''apply'' in order to support creating naturals with the call ''Nat(.)'' from different other types. | ||
| - | **8.1.** Create a companion object for ''Nat'' and add appropriate apply functions in order to make the expression ''Nat(1) + Zero + Nat("2")'' successfully compile and run. | + | **8.1.1.** Create a companion object for ''Nat'' and add appropriate apply functions in order to make the expression ''Nat(1) + Zero + Nat("2")'' successfully compile and run. | 
| + | |||
| + | **8.1.2.** Define a function that takes a list of integers and converts them to a list of type ''List[Option[Nat]]''. If an integer ''x'' is positive, it should become a value ''Some(x)''. Otherwise it should become ''None''. | ||
| + | |||
| + | <code scala> | ||
| + | def fromList(l: List[Integer]): List[Option[Nat]] = ??? | ||
| + | </code> | ||
| + | |||
| + | **8.1.3.** Define a function which takes a list of ''Option[Nat]'' and converts it to ''Option[List[Nat]]''. The logic here is that if the list contains at least one ''None'' value (hence **some** conversion from integer failed), then the result should be ''None'' . Otherwise, it should be a list containing all valid naturals: | ||
| + | <code scala> | ||
| + | def fromOptions(l: List[Option[Nat]]): Option[List[Nat]] = ??? | ||
| + | </code> | ||
| ===== 8.2. Dictionaries ===== | ===== 8.2. Dictionaries ===== | ||