Why coding------recursion and recursion in enumerations

Source: Internet
Author: User

Title: "Why coding-like this--recursion and recursion in enumerations"
Date:2015-08-28 21:34:16
Categories: "Why coding like this"
Tags: [Swift advanced]

Topic 1:

Enter an array of xs:[int] to sum all the elements.

discuss
    • Idea one: Hey, buddy, iterate through the array, add it up, so easy!

Code

func sum1(xs:[Int])->Int{    varsum0    forin xs{        sum += x    }}
    • Idea two: Assuming that there is already an array summation function sum2, can I break it down like this:
      sum([2,3,5]) = 2 + sum([3,5]) = 2 + 3 + sum([5]) = 2 + 3 + 5 + sum([])
      We recursive the array of arrays into elements of the first element and the remaining array elements until we have an empty array summation ( 此时返回0 ) to complete the sum of the [2,3,5] pairs. Before we write the specific summation function, we want to expand the next array in small, add a decompose computed property, its function is to return to the current array of decomposition results, a type (head:T,tail:[T])? of tuple, because the array may exist empty array, at this time decomposition must return nil, It is therefore not difficult to understand that this tuple is an optional type.

Code

Array{    var decompose:(head:T,tail:[T])?{        //通过数组元素个数来判断是否为空数组 空数组则返回nil         //否则返回首元素 和剩余元素组成的数组        //特殊的是单个元素数组[x] 返回 x 和空数组[]        return0) ? (self[0],Array(self[1..<count])) : nil    }}

The next step is to use recursion to implement the SUM2 function, with the above understanding that Gray is often good to write:

func sum2(xs:[Int])->Int{    //如果是空数组 元组为nil 返回0值即可    iflet (head,tail) = xs.decompose{        return (head + sum2(tail))  //递归    }else{        return0    }}

The above is a taste of recursion the next step is to understand the first enumeration recursive usage in the swift2.0 syntax

Topic 2:

Evaluates the expression (5 + 4) * 2 using recursion in the enumeration.

discuss

The first analysis of the expression, mainly divided into numbers (number) and operators +、-、*、/ , the operators are often on both sides of each of the digits. So if we use enumerations, we'll define

enum ArithmeticExpression{    case Number(Int)    case Addition(ArithmeticExpression, ArithmeticExpression)    case Multiplication(ArithmeticExpression, ArithmeticExpression)    //这里你还可以添加减法和除法}

Notice the indirect keyword, which is the indicator enumeration recursion. Define the data structure, we also need a function for expression parsing, the function passed in ArithmeticExpression the type value, may be number bound numbers, for example, .Number(5) represented as a single number 5, or an operator bound to the left and right of the operation data, such as .Addition(5,4) = 5 + 4.

Func Evaluate (expression:arithmeticexpression), Int {SwitchExpression { Case. Number (Letvalue):return value     Case. Addition (let left, let Right):returnEvaluate (left) + evaluate ( Right) Case. Multiplication (let left, let Right):returnEvaluate (left) * Evaluate ( Right)    }}//Expression (5 + 4) * 2LetFive= Arithmeticexpression.number (5) Let Four= Arithmeticexpression.number (4) Letsum= Arithmeticexpression.addition (Five, Four) Let Product = Arithmeticexpression.multiplication (sum, Arithmeticexpression.number (2)) Print (Evaluate (product))//Prints "

I have to say that the official example may disappoint a lot of friends, which is not an example of a complete pass-through expression giving you a value, but it allows you to understand recursion in enumerations.

The above code can only be run under the new beta version of Xcode7. But, yes, I have a way to make the code work for the swift1.2 syntax, just in a small package.

class  box  <t  >{let unbox: t  init (
      
       _ 
       value : t )  { Self.unbox = t }}//due to swift1.2 is an enum that does not support generic association values enumtypeerror< t  >{case Type1 (NSError )  case Type2 (t ) }// But we can change the enum Enumtypesuccess<t  >{case Type1nserror )  case Type2 (box  <t  >) }//Similarly you can encapsulate the enumeration above as challenge! 

This book is based on official documentation and functional programming in Swift, which is shared only as a learning note. To tell the truth this article slightly water, actually earlier is want to make scrollview of the secret article, want to discovering from the basic to all, but after writing a little water, a lot of their own understand but did not express, so intend to melted down re-create! I'm sure I'll meet you soon. In addition swift2.0 the latest syntax I have updated to GitHub is the official 8.24 latest version. GitHub address, I hope you can also follow my Weibo address under star.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Why coding------recursion and recursion in enumerations

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.