Coursera open course Functional Programming Principles in Scala exercise answer: Week 2

Source: Internet
Author: User

Introduction

OK. The time has passed for another week. The first week has a May Day holiday, so I feel that the time is more than enough. In the middle of this week, no holiday can only be digested by evening and weekend time. In fact, it is still a little nervous! Later, we found that the video of each course also had corresponding courseware (Slide) and subtitles (subtitles) that could be downloaded. In this way, the download of video learning and online learning is only inferior to the Exercise in the middle of the course.

Week 2 mainly talks about functions. functions are first-class citizen in Scala and can appear in any domain. This course is actually based on Scala's functional programming principles. Well, let's not talk about it. Go to the exercise Analysis page.

This week's job mainly uses functions to represent a set. You can pass an integer value to a Boolean value to verify whether the integer value belongs to this set. Well, it's too difficult. Here is a chestnut:

(x: Int) => x < 0


This is an anonymous function that maps an input x to a Boolean value to determine whether x belongs to the set represented by this function. Obviously, this set is a negative integer set.

Starting from here, a function from Int to Boolean is used as the expression of the set and an alias is assigned to it:

type Set = Int => Boolean


Therefore, the set defined in this job should be given in the form of a function. The function mentioned above is a first-class citizen. Of course, it can be used as a return value. The method used to determine whether a value is in a given set is as follows:

def contains(s: Set, elem: Int): Boolean = s(elem)


We can see that the contains function is passed into a Set and an Int as the parameter. As mentioned above, Set is a function of the Int type input, so s is applied to elem, returns a Boolean value.

Exercise 2.1 Basic Functions On Sets

Exercise 2.1 defines some simple operations of the set.

SingletonSet

Define a set at the beginning ~ This set is a singleton set and can only store one value. The signature is as follows:

def singletonSet(elem: Int): Set

You can use an Int type parameter to initialize this function. The returned result is a Set type, that is, a function of Int => Boolean. We already know that the set contains only the elem element, so we only need to determine whether an element is equal to or not elem.

Write your own code ......

Union, intersect and diff

We have defined a simple set above. Next we can generate a new set through continuous combination of simple sets. The three commonly used operations are union, intersect, and diff. The prototype is as follows:

def union(s: Set, t: Set): Setdef intersect(s: Set, t: Set): Setdef diff(s: Set, t: Set): Set

The preceding three operations obtain a new Set by combining two sets, indicating the Union, intersection, and difference Set of the two sets.

1. union is a set of elements in s or in t, so you only need to determine whether an element is in either of them.

2. intersect is a set of elements in s and in t. Therefore, you need to determine whether an element is in both

3. diff is a set of elements in s that are not in t. You need to determine whether an element is in s and not in t.

Code, write it by yourself.

Filter

The next step is to implement a filter function, that is, to select elements in the Set s that conform to assertion p. These elements are also a set. The filter prototype is as follows:

def filter(s: Set, p: Int => Boolean): Set

This is actually relatively simple. It is essentially the deformation of intersect, but the second input parameter of intersect is the alias of the second input parameter of filter.

Exercise 2.2 Queries and Transformations on Sets

Job 2.2 completes some operations on the Set.

Forall

The first function is given an asserted to determine whether all elements in the Set satisfy this asserted. The signature is as follows:

def forall(s: Set, p: Int => Boolean): Boolean

The way we define the Set determines that we cannot list all the elements in the Set. We can only determine whether the given element belongs to this Set. Therefore, to complete this function, we need to traverse all the integer numbers. This is unrealistic, so it is limited to-1000 to 1000.

For the above forall function, the question provides a framework, you only need to put the corresponding part (namely ??? Part:

def forall(s: Set, p: Int => Boolean): Boolean = { def iter(a: Int): Boolean = {   if (???) ???   else if (???) ???   else iter(???) } iter(???)
}


We can see that forall internally defines a function iter and uses an iter instance as the return value of forall. (Note that the attention function is the concept of a first-class citizen !)

Then, based on the above prompts, We need to traverse the integer from-1000 to 1000 and judge whether it meets the asserted p in sequence. Of course, the precondition is that this integer also belongs to the set s. P is a function that maps an Int type to a Boolean type. You only need to pass the integer data to it and determine whether the return value of the integer meets p. To determine whether a number belongs to the set, use the contains function defined in Exercise 2.1.

Main. scala also defines an upper bound:

  /**   * The bounds for `forall` and `exists` are +/- 1000.   */  val bound = 1000


In fact, this is relatively simple. You only need to judge from-1000 to 1000 whether all the elements belonging to the set s comply with assertion p in turn. If one of the conditions does not meet the preceding conditions, false is returned. If both conditions are met, true is returned.

Implement it on your own.

Exists

The second function to be implemented is exists, that is, to determine whether the set s contains elements that conform to the given assertions. The signature is as follows:

def exists(s: Set, p: Int => Boolean): Boolean


Note that the question requires that exists be implemented by calling forall. Familiar with this scenario ...... This is not the question in the high school textbook: "The probability that all faces of N coins are facing up ", is the relationship the same as the probability of throwing N coins with a face-down relationship?

OK, analyze it. Determine whether the set s contains elements that conform to the given assertions, that is, to determine whether all elements in the Set s do not conform to the given assertions.

If all elements in s do not conform to the given assertions, false is returned; otherwise, true is returned.

Do you understand? Next question.

Map

The last question is to write a map function and map the given set to another set. The signature is as follows:

def map(s: Set, f: Int => Int): Set

The second parameter f is used to map the elements of the original set to the functions of the new set (first-class citizen !)

The question looks simple, just to judge whether the elements in s are equal to the input integer after f ing.

This includes two steps:

1. Is there any element in s that meets a specific condition (assertion )?

2. The specific condition (assertion) is mapped to f, which is equal to the input parameter.

Remember that the return type is Set, that is, Int => Boolean type function (first-class citizen !)!

Conclusion

In general, Scala is different from other object-oriented languages. One of the biggest features is that it integrates a lot of functional programming concepts and methods. This is especially important when using Scala! Scala can be seen as a combination of O-learning (Object-Oriented Programming) and F-learning (functional programming!

PS: The included FunSetSuite. scala only has a few test cases, and some are labeled with ignore. If you are interested, you can try to write some unit tests to ensure that some special cases can be covered, in this way, we will not repeatedly submit imperfect answers on Coursera's server!

PPS!

Chapter 2 Title: http://download.csdn.net/detail/doggie_wangtao/7343177

Coursera open course Functional Programming Principles in Scala exercise answer: Week 1

Statement:

This article is original, prohibited for any commercial use, reproduced please indicate the source: http://blog.csdn.net/asongoficeandfire/article/details/25661661

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.