Original: swift:using String Ranges the functional
A few weeks ago, I introduced "How to use range to intercept strings in Swift." At the time, it was confusing to use range in swift, but at least we found a way to work.
However, when I learned a lot about functional programming in the past few weeks, I suddenly realized that the range in Swift was so difficult to use in order to guide us to using it in a more figurative way--specifically, in a way that was similar to functional programming.
By watching the edx fp101x course, the first piece of knowledge I learned was the concept of head and tail. In fact, the first lesson took five minutes to introduce the concept of head and tail , and these two concepts have been mentioned in subsequent lessons. The concept itself is very simple: the head is the first element of the list, and tail is a list that is made up of elements other than the first element in the list.
head[1,2,3,4,5]//1 tail[1,2,3,4,5]//[2,3,4,5]
In functional programming, it is very rare to use the classic for loop to handle the problem, instead of using head, tail, and recursion to manipulate the elements in the list.
Let's look at a specific example: get the first X-bit character in a word. If you do not consider using ranges in swift (because it is not easy to use), you might do so in the following way:
func getsubstringuptoindex (Index: Int, fromstring str: string) -> string{ var substring = "" for (I, letter) in enumerate (str) { substring.append (letter) if i == index - 1 { break } } return substring} getsubstringuptoindex (5, fromstring: "Hello, natashatherobot")// Hello
Now look at the idea of functional programming, using head, tail, and recursion to achieve:
Func Getsubstringuptoindex (Index:int, fromstring str:string), string{let (head, tail) = (Str[str.startindex] , Dropfirst (str)) If index = = 1 {return string (head)} return string (head) + Getsubstrin Guptoindex (Index-1, Fromstring:tail)} getsubstringuptoindex (5, fromstring: "Hello, Natashatherobot")//Hello
Having seen the above example, I think we have some knowledge of why Swift designed such a difficult ranges, startIndex and Endindex.
For the example above, I can also use the method described in "How to use range to intercept strings in Swift" , but instead of a for-loop solution by using the functional solution described above, We can begin to think more about how to use the idea of functional programming to solve problems. After all, this way of focusing on the head and tail (and no simpler way to solve the problem) is reflected in many swift APIs.
[Swift] uses ranges in strings in a functional programmatic way