Learning notes for the publication (2.2.1)

Source: Internet
Author: User
Learning notes for the publication (2.2.1)

Zhou yinhui

1, two closures

The two types of closure (closure) come from
The world of mathematics is a computer world.
Although they are all called closures, they almost mean completely different
The two things are described as follows.

  • 1.1 closure in mathematics:
    We assume there is a set S and an operation p. Assume that
    The new elements generated after P is applied to the elements in s are still in the Set S.
    We say that the Set S is "closed" (closed
    ). For example, the natural number set N is closed in addition, because
    The result of the number addition is still a natural number. However, if the natural number set is under subtraction
    It is not closed, because the result of two natural numbers subtraction may exceed
    Natural Number range (for example, the obtained value is negative ). So we want to do it.
    This method expands a natural number set to the set S' (which means that N is
    The subset of S'), so that s' can be closed under subtraction.
    We can find the Integer Set Z and the real number set R.
    Among the many sets found, there is a range of "minimum"
    So that it just closes under addition. This "minimum set
    "We call it the closure of natural number set N under subtraction.
    ". Generally, if the set S is
    If it is not closed, we can usually find (or we may not find it)
    Contains the minimum set of S, so that S is closed under the P operation.
    We call s' the closure of the Set S under P. Let's look back.
    The word "closed" can be understood as follows:
    The closure of the Set S under P is equal to the set itself, so let's say
    The set S is "closed" under P ".
    We can
    This is a simple understanding: assume there is an operation P defined on the set S, such
    If the P operation result is included in S, the P operation satisfies
    Closure Properties ". From the mathematical point of view, if p is computed
    For elements other than S, the definition of P is unreasonable.
    At least it should be defined on the closure of S. For example, we define the subtraction in
    However, in terms of quantity, it is unreasonable because it may generate a non-natural number.
    That is, if you come to invent "subtraction ",
    , You should at least define it on an integer.

  • 1.2 closure in a computer:
    Let's first look at a JavaScript function: Function F ()
    {
    VaR A =   5
    Return   Function G (B)
    {
    Al
    ERT (
    + B)
    }
    }

    Suppose we call f () (6) as follows. How can we evaluate it?
    Call function f first. In function f, we declare a local variable,
    The value is 5, and function f then returns the function g as the return value.
    The lifecycle of variable A ends, and the function g that is returned is called.
    Its parameter is 6. After Entering the function body of G, it sums a and 6 and adds the value
    When passed as a parameter to alert, the summation operation seems a bit depressing.
    : Where can I find variable? It is a local variable in function f and declares
    The cycle has long ended.
    Indeed, without the concept of closure, the above call is indeed not
    Valid, but the actual debugging tells us that Code Can run well,
    Let me explain it slowly.
    Ideally, we always want the function to be "pure
    ", A pure function has the following properties: first,
    For the same input, the same output is always returned. Secondly, the result of evaluation is not
    Will produce any side effects. Functions of this nature are called
    "Pure function" (pure function), pure
    Functions have many advantages, such as tuning and parallel operations.
    However, in the actual programming process, it is difficult to implement a pure function.
    It is often dependent on some external variables, that is, the so-called "Free change ".
    Quantity (refer to learning notes 1.1.7 ~ 1.1.8), like above
    Function g, which depends on the free variable A (for the same input may be
    The output is not the same, so it is "not pure"), I
    The free variables on which it depends can be simply understood as "correct
    The environment or context required to call the function.
    When calling the function, the free variables must be correctly evaluated.
    (Or call), that is, we must create
    Required environment. If not Program An error is reported, for example
    "Referencing undefined variables" and so on. Since the above
    If JavaScript code can be correctly executed, it indicates that JavaScript has
    There is a certain ability to create the necessary environment for function g, which is
    The ability to create "closures. When function f returns
    The current function g depends on its local variable A (note that the four words of the local variable are very heavy
    Yes, this indicates that a is the constraint variable of F), and the variable a and function g
    Package it into a whole to form a so-called "closure ".
    A and G are packaged together, so when G is called
    Access to a, that is, its computing environment can be well created
    .
    Therefore, in general, computers Programming Language "
    A closure refers to a combination of a code block and a code block runtime environment.
    Entity. Note that the running environment here does not refer to all the loops
    The complete set of environment is actually just one element that must be packaged here
    . For example, in the code above, how does function g also depend on an external variable?
    And C is the free variable of function F, or even a global variable.
    C won't be included in this closure, and there is no need to include it.
    Finally, let's take a classic Note: The data containing behaviors is called objects, including
    Data behavior is called closure.

2. List operations

For more information about how to construct a list from a sequence, see section 2.2.1 of the SiCp.
I am very clear. Here are some operations on the list.

  • Flatten: flatten the list"
    For example, the result of (flatten '(2 3) 4 5) should be (2 3)
    4 5)
    (Define (flatten theList)
    (Cond
    (Null? TheList )'())
    (Pair? (Car theList ))
    (Append (flatten (CAR theList) (flatten (CDR
    TheList ))))
    (Else (Cons (CAR theList)
    (Flatten (CDR theList ))))))

  • Depth: Evaluate the nested depth of the List
    For example, the result of (depth '(2 3) 4 5 (6 (7 8) should be
    3
    (Define (depth theList)
    (If (not (pair? TheList ))
    0
    (Max (+ 1
    (Depth (CAR theList )))
    (Depth
    (CDR theList )))))

  • Reverse to flip the list
    For example, the result of (reverse '(1 2 3 4) should be (4 3
    2)
    (Define (reverse theList)
    (If (null? TheList)
    '()
    (Append
    (Reverse (CDR theList) (List (CAR theList )))))

3. Practice 2.17

"Last pair" means that the CDR of the pair is
Null, so:
(Define (lastpair theList)
(If (null? (CDR theList ))
TheList
(Lastpair (CDR
TheList ))))

For example, the result of (lastpair '(1 2 3 4) is (4 ),
(Lastpair '(2 3) 4 5 (6 (7 8)
(6 (7 8 )))

 

4. Practice 2.18

The answer has been given above. The general solution is as follows, assuming that the column
Table L: '(a B c d) its flip equals to appending the first element of list l
A new list after the reverse list of the list composed of the remaining elements,
It sounds good. It is represented by a mathematical formula R (L) = append (
R (m) First), where R (l) indicates the inversion of list l, append (
B) append B to the end of a to form a new list. First indicates
The first element. M indicates that the list is composed of the remaining elements after the first element is removed.
New list, so the code written as scheme is as follows:
(Define (reverse theList)
(If (null? TheList)
'()
(Append (reverse
(CDR theList) (List (CAR theList )))))

 

5. Practice 2.19

First-denomination, the first denomination, that is,
An element, car
Except for the first denomination
New list, CDR
No-more? There are no other denominations in the list, that is, the empty list '()

 

6. Practice 2.20

Heheh, a very interesting question, should be well completed
First, we need to understand the simple "accumulate operation" under "increment ".
"Example:
Assume that we accumulate the number from one exercise to another, for example, from 1
After accumulating 5 (the result is 15), we can write the following iteration calculation:
Method
(Define (add-iter from to result)
(If (> from)
Result
(Add-ITER (+ from
1) to (+ result from ))))

(Define (add from)
(Add-iter from to 0 ))

Note that the add-iter above is the most
The final result, we set an iterator named result to save
Value. When we enter the next iteration, we will
"From is added with 1, and the value to be accumulated (here the accumulated value is
The value is the same as that of the pedometer) and is accumulated to the result. When iteration ends
The result is returned.
OK. Now I want to change the above question a little, just accumulating an even number (for example, from
1 to 5, the result should be 6 ):
(Define (add-even-iter from to result)
(If (> from)
Result
(Add-even-ITER (+
From 1)
(If (even? From)
(+
Result from)
Result ))))

(Define (add-even from)
(Add-even-iter from to 0 ))

We found that the last version is different from the previous one.
If the value to be accumulated is an even number, the value is accumulated.
Break it down, with the condition: even number; Initial Value: 0; satisfying
Operation: arithmetic addition

Now let's look back at our current questions. We want to return to the list
The first element is the Child list with the same parity.
Similarly, let's break down the problem by the condition: odd from the first element
Similar; Initial Value: Empty list nil; operation when conditions are met: Column
Append table

Then, let's see the following:

(Define (f a B)
(Equal? (Even? A) (even? B )))

(Define (same-parity-iter firstone others result)
; Note that there is no decimal point
(If (= (length others) 1)
(If (F
Firstone (CAR others ))
(Append result (List (CAR others )))
Result)
(Same-parity-iter
Firstone (CDR others)
(If (F
Firstone (CAR others ))

(Append result (List (CAR others )))
Result ))))

(Define (same-parity firstone. Others );
Note that there is a decimal point.
(Same-parity-iter firstone others (list
Firstone )))

F is a function used to determine whether two parity values are the same.

Note that some code segments in same-parity-ITER are duplicated. We can
To refactor it, assume G. The complete code is as follows:
(Define (f a B)
(Equal? (Even? A) (even? B )))

(Define (G firstone others result)
(If (F firstone (CAR others ))
(Append result (List (Car
Others )))
Result ))

(Define (same-parity-iter firstone others
Result)
(If (= (length others) 1)
(G firstone others
Result)
(Same-parity-iter
Firstone (CDR others)
(G firstone
Others result ))))

(Define (same-parity firstone. Others)
(Same-parity-iter firstone others (list
Firstone )))

; Test
(Same-parity 1 2 3 4 5 6 7 8 9)

7. Exercise 2.21

It's relatively simple. I posted the answer directly:
(Define (Square A) (* ))
(Define nil '())

(Define (square-list items)
(If (null? Items)
Nil
(Cons (square (Car
Items) (square-List (CDR items )))))

(Define (square-list2 items)
(MAP square items ))

(Square-List (List 1 2 3 4 ))
(Square-list2 (List 1 2 3 4 ))

 

8. Practice 2.22

I usually do this:

(Define (Square A) (* ))
(Define nil '())

(Define (square-list items)
(Define (ITER things answer)
(If (null? Things)

Answer
(ITER
(CDR things)
(Append answer
(List (square (car things )))))))
(ITER items nil ))

(Square-List (List 1 2 3 4 ))

 

9. Practice 2.23

(Foreach proc theList)
The element application process proc, that is, first apply the first element in the list
Proc, and then the Child list composed of the remaining elements after removing the first element
Sublist call (foreach proc sublist). In addition, you must determine
Whether the first element exists (whether the list length is greater than 0) and whether it exists
Sub-List (whether the list length is greater than 1 ):

(Define (foreach proc theList)
(If (> (length theList) 0)
(Begin (Proc (Car
TheList ))
(If (> (length theList)
1)
(Foreach
Proc (CDR theList ))))))
; Test
(Foreach (lambda (x) (newline) (display X) (List
57 321 88 ))

 Note: This is a reading note, so the content is only
Personal Understanding does not represent the opinions of P.
May be modified.

 

 

 

 

 

 

 

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.