Clojure Learning 03: Data Structures (Collections)

Source: Internet
Author: User
Tags set set

Clojure provides several powerful data structures (collections)

I. Types of collections

1. Vector

Equivalent to an array such as: [2 3 5], ["Ad" "Adas" "Adadsads"]

2. List

Equivalent to a linked list, such as: ' (2 3 5), ' ("Ad" "Adas" "Adadsads")

Compared to vectors, [] becomes (), and because () the symbol is used for function calls, in order to differentiate, it needs to be preceded by a single quotation mark '

3. Map

Syntax format such as: {: a 1:b 1}

Map is 1 or more key-value pairs, where the key identifier is previously required to have: identity. The key in map itself is a function that allows you to find the value it corresponds to.

Such as:

User=> (def data {: A 1:b 2}) User+ = (: a data)1user+ (: A {: a 1:b 2})1u Ser= (: a {: a 3:b 2})3

The first statement above defines a value of data, which is a map. The second statement is to get the keyword: a value, here: A is a function.
The last two statements query the value of the key directly from the map literal.

4. Set

Syntax format such as: #{value 1 Value 2 ....}

User=> #{1 2 3}
#{1 3 2}

Description, the Clojure collection object has the following characteristics compared to the Java collection:

1) The contents of the immutable collection are not modifiable after initialization, and subsequent operations on it will result in a new collection

2) heterogeneous Multi-phase (heterogeneous), the elements in the collection do not require the same data type, can be a collection of different types of data

3) Persistent Persistent, the contents of the collection is not modifiable, the related operation will produce a new collection, but not the way to copy, but a bit like the configuration management mechanism, only the new changes, the old part of the original data. So all the historical data can be preserved intact.

The three major operations of the set

Clojure provides a number of built-in common functions to manipulate various collections. Note that no function can modify the collection because the collection of Clojure is not modifiable, but there are many functions that can generate a new collection.

1. Filter function

The filter function is one of the three important operations for set operations in functional programming, and almost all languages that support functional programming have similar methods.

The function is to filter out the elements that satisfy the condition to form a new set of returns.

The filter function requires two parameters, the first of which is a filter function to check if the element is compliant, and the second is the collection itself. The result returns a list.

As in the following example:

Example 1:

User=> (Def stooges ["Moe" "Larry" "Curly" "Shemp"])
# ' User/stooges
User=> (Filter # (> (count%) 3) Stooges)
("Larry" "Curly" "Shemp")

The Count function in the above code is the length of the computed string, # (> (count%) 3) is an anonymous function that satisfies the condition only if the string is longer than 3.

Example 2:

User=> (Def Years [1940 1944 1961 1985 1987])
# ' User/years
User=> (Filter # (even%) years)
(1940 1944)

2. Map

The map function is one of the three important operations of the set operation in functional programming, and almost all languages that support functional programming have similar methods.

The function is to handle each element in the collection, and finally get a new set (note that the collection type is a list), the new collection has the same number of elements as the original set, but the content can be different (including the type of the element).

So the first parameter of the map function is the processing function for the element transformation, and the next parameter is the set to be processed (one or more).

For example, let's say:

Example 1:

(Defn fun [item] (* Item 2))//defines a function that returns the value of multiplying the input parameter by 2

(Map fun [1 2 3]) The//map function uses the fun function, and the return result after the last map function call is (2 4 6)

As you can see, the collection being processed is a vector, but the collection type returned after processing is list

Example 2:

User=> (Map Fun #{1 2 3}) (2 6 4)

As you can see, the collection type returned by set is also a list, and because the set itself is unordered, the returned list result sequence number is inconsistent with the set surface.

Example 3:

user=> (Map + [2 4] [5 6] [1 2]) (8 12)

user=> (Map + [2 4 7] [5 6] [1 2 3 4]) (8 12)

The first argument passed in the above two examples is that the function is +, followed by multiple collections. The final result is calculated according to the smallest set element.

Example 4:

User=> (Map # (*% 2) [1 2 3]) (2 4 6)

The above code is passed to map in an anonymous function # (*% 2). In the actual set map operation, anonymous functions are passed in a large number of scenarios.

The anonymous function in Clojure is similar to a lambda expression in Python, java8.

3. Reduce

The reduce function is one of the three important operations for set operations in functional programming, and almost all languages that support functional programming have similar methods.

The function is to handle the collection and get a computed value. such as Sum, Count, Max, and Min are exceptions to the reduce operation, except that these operations are very common and common and are referred to as specialized methods.

Such as:

User=> (Reduce # (+%1%2) [1 2 3])
6

The above action sums the collection. The first parameter of reduce is a function, which is an anonymous function, the first parameter of the anonymous (in lieu of 1%) is the return value of each iteration, and%2 is the element.

Each time an element is manipulated, 1% is re-passed as a parameter, and the value of%1 is returned as the function value of reduce after the last element has been processed.

User=> (Reduce # (*%1%2) [2 4 6])
48

The above action is the product of the elements in the collection.

User=> (Reduce # (if (>%1%2)%1%2) [10 2 54 3 6])
54
User=> (Reduce # (if (<%1%2)%1%2) [10 2 54 3 6])
2

The above two operations are the maximum and minimum values.

Third, the collection of other operations

The operations of the collections described below are some of the exceptions to these three major operations.

1. Count function

This function is used to get the number of elements in the collection

User=> (Count [yellow "true])
3
User=> (count ' (yellow "true))
3
User=> (Count #{19 "yellow" true})
3
User=> (Count {: a 1:b 2})
2

As can be seen from the above example, the Count function is appropriate for these four collections.

2, Reverse

The function is to reverse-arrange the data in the collection and return a new collection. Because the map and set itself are unordered data structures, the reverse function only makes sense for vectors and lists.

User=> (Reverse [2 4 7])
(7 4 2)
user=> (Reverse ' (2 4 7))
(7 4 2)

3. Map

The function of the map function is to handle each element in the collection, and finally get a new set (note that the collection type is a list), the new set of elements and the original set, but the content can be different (including the type of the element).

So the first parameter of the map function is the processing function for the element transformation, and the next parameter is the set to be processed (one or more).

For example, let's say:

Example 1:

(Defn fun [item] (* Item 2))//defines a function that returns the value of multiplying the input parameter by 2

(Map fun [1 2 3]) The//map function uses the fun function, and the return result after the last map function call is (2 4 6)

As you can see, the collection being processed is a vector, but the collection type returned after processing is list

Example 2:

User=> (Map Fun #{1 2 3})
(2 6 4)

As you can see, the collection type returned by set is also a list, and because the set itself is unordered, the returned list result sequence number is inconsistent with the set surface.

Example 3:

user=> (Map + [2 4] [5 6] [1 2])
(8 12)

user=> (Map + [2 4 7] [5 6] [1 2 3 4])
(8 12)

The first argument passed in the above two examples is that the function is +, followed by multiple collections. The final result is calculated according to the smallest set element.

Example 4:

User=> (Map # (*% 2) [1 2 3])
(2 4 6)

The above code is passed to map in an anonymous function # (*% 2). In the actual set map operation, anonymous functions are passed in a large number of scenarios .

The anonymous function in Clojure is similar to a lambda expression in Python, java8.

4. Apply

The function is to pass a function and a collection to it, and the result returned after the function has been manipulated for the entire collection is the return result of the Apply function.

User=> (Apply + [2 4 6])
12
user=> (Apply * [2 4 6])
48
User=> (Apply-[2 4 6])
-8

5. Get a single element from the collection

User=> (Def stooges ["Moe" "Larry" "Curly" "Shemp"])
# ' User/stooges
User=> (First stooges)
"Moe"
User=> (Second stooges)
"Larry"
User=> (Last Stooges)
"Shemp"
User=> (Nth stooges 2)
"Curly"

The last method, the 2nd parameter of nth, indicates the acquisition of the first element (starting at 0, where 2 represents the 3rd element).

6. Get multiple elements from the collection

User=> (Def stooges ["Moe" "Larry" "Curly" "Shemp"])
# ' User/stooges


User=> (Next stooges)
("Larry" "Curly" "Shemp")

User=> (Nthnext stooges 1)
("Larry" "Curly" "Shemp")

User=> (Nthnext stooges 2)
("Curly" "Shemp")
User=> (Butlast stooges)
("Moe" "Larry" "Curly")

User=> (Drop-last 1 stooges)
("Moe" "Larry" "Curly")
User=> (Drop-last 2 stooges)
("Moe" "Larry")

7, some

This function can be used to determine whether a collection contains an element, a function to be used as a parameter, and another parameter to be the collection itself. Such as:

User=> (Def stooges ["Moe" "Larry" "Curly" "Shemp"])
# ' User/stooges
User=> (some # (=% "Moe") stooges)
True
User=> (some # (=% "Mark") stooges)
Nil

As you can see, returns true if it exists, otherwise nil is returned (why not return false?). )。

The above wording will look awkward and can be used to achieve the same goal:

User=> (contains? (Set Stooges) "Moe")
True
User=> (contains? (Set Stooges) "Mark")
False

Above, using the Set method to convert a vector to a set set, and then using the CONTAINS function to judge, it will look clearer and simpler.

Another difference is that when an element does not exist, it returns not nil, but false.

Clojure Learning 03: Data Structures (Collections)

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.