Swift 3 Fun Algorithms: Abstract Syntax Tree (Warning: Somewhat Difficult Recursion)

Поділитися
Вставка
  • Опубліковано 17 лис 2024

КОМЕНТАРІ • 69

  • @johnnyAustria80
    @johnnyAustria80 7 років тому +17

    Fantastic video Brian, appreciate all the hard work you put into your videos.
    Couldn't help myself in refactoring the evaluate method.
    func evaluate(node: Node) -> Float {
    if node.value != nil {
    return node.value!
    }
    func performBinaryOperation(operation: String) -> (Float, Float) -> Float {
    switch operation {
    case "+":
    return { $0 + $1 }
    case "-":
    return { $0 - $1 }
    case "*":
    return { $0 * $1 }
    case "/":
    return {(lhs: Float, rhs: Float) -> Float in
    if rhs == 0 {
    fatalError("Divide by zero")
    }
    else {
    return lhs / rhs
    }
    }
    default:
    fatalError("Invalid Operator: \"\(operation)\"")
    }
    }
    let performBinaryOperationOn = performBinaryOperation(operation: node.operation!)
    return performBinaryOperationOn(evaluate(node: node.leftChild!), evaluate(node: node.rightChild!))
    }
    Not sure its any shorter, but I still had fun writing it.

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому +3

      This is excellent, really happy to hear you had fun rewriting it. Really like the functional approach of solving this challenge. I didn't even know you could write functions within functions like this...

    • @johnnyAustria80
      @johnnyAustria80 7 років тому

      Thanks for the feedback

  • @andreychirkov1904
    @andreychirkov1904 7 років тому +1

    Fantastic! Looking forward next Friday episode

  • @kryptoshi4706
    @kryptoshi4706 7 років тому +2

    You are a great teacher Brain ! Thank you for putting so much work in, swift is such a beautiful language. I remember during college programming this in C was a pain !!

  • @stevenhans7669
    @stevenhans7669 7 років тому +1

    good video!
    as a computer science student this is a new source of learning how to code new languages and algorithms
    thank you very much, I found this very informative
    keep it up Brian, i'd like to see more videos like this in the future

  • @xShorDz
    @xShorDz 7 років тому +1

    I think this is the best gift for my today's birthday, thank you Brian!

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому +2

      You're very welcome Andrea, I'll bring you another present next year.

  • @ProgrammerinToronto
    @ProgrammerinToronto 7 років тому +1

    Thank you for your awesome algorithm show! can't wait to see next time.

  • @kav04
    @kav04 6 років тому +1

    Brian you killed it !

  • @MThomasson88
    @MThomasson88 7 років тому +1

    Excellent video once again. I've learnt so much from you! Looking forward to next vid.

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому +1

      Great to hear the positive feedback Martin, next vid next week.

  • @yanxu9167
    @yanxu9167 2 роки тому +1

    So clear! My professor is useless. Thank you.

  • @robertcharmers3264
    @robertcharmers3264 7 років тому +2

    Nice explanation, certainly refreshed my memory from uni days.
    Would be nice to see a video which addresses the substantially more complex task of producing the actual AST which must,at least in this case, take into account the order of operations (i.e BODMAS) since the algorithm you present here assumes the operations have been specified in the correct order.

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому

      Hi Robert, yeah I would like to get my hands on more complicated examples of trees. I've been out of college for quite some time and need to do some research on theory again.

    • @robertcharmers3264
      @robertcharmers3264 7 років тому

      Haha same here man, its amazing how easy it is for your memory to slip especially when your not actively writing these algorithms on a daily basis.
      Like I say, I think your implementation, which essentially *traverses* the tree, is perfectly adequate for production use as long as the algorithm that parses the raw expressions and tokens to *produce* the actual AST being traversed takes into account the order of operations.
      This is what I'm attempting to do at present for a project I'm working on; I need to be able to take a bunch of arbitrary arithmetic expressions and parse and order them (according to BODMAS) to produce a tree; once I've done that then an algorithm not to dissimilar to the one you present here may be used to traverse and process the resulting tree.
      Anyway, great video!!

  • @Jiawii
    @Jiawii 3 роки тому

    The audio of this video is so good

  • @PythonPlusPlus
    @PythonPlusPlus 5 років тому

    This can be solved beautifully with indirect enums:
    indirect enum ArithmeticStatement {
    case Add(ArithmeticStatement, ArithmeticStatement)
    case Subtract(ArithmeticStatement, ArithmeticStatement)
    case Multiply(ArithmeticStatement, ArithmeticStatement)
    case Divide(ArithmeticStatement, ArithmeticStatement)
    case Value(Float)
    }
    let calculation: ArithmeticStatement = .Add(.Multiply(.Value(25),
    .Value(6)),
    .Value(5))
    func evaluate(_ statement: ArithmeticStatement) -> Float {
    switch statement {
    case .Add(let a, let b):
    return evaluate(a) + evaluate(b)
    case .Subtract(let a, let b):
    return evaluate(a) - evaluate(b)
    case .Multiply(let a, let b):
    return evaluate(a) * evaluate(b)
    case .Divide(let a, let b):
    return evaluate(a) / evaluate(b)
    case .Value(let value):
    return value
    }
    }
    print("25 * 6 + 5 = \(evaluate(calculation))") // 25 * 6 + 5 = 155.0

  • @aleksejsigaj1373
    @aleksejsigaj1373 5 місяців тому

    Much easier to weite the Node structure as
    let value: Value
    let leftCh...
    let rightCh...
    enum Value {
    case number(Int)
    vase operation(Operation)
    }
    enum Operation {
    case plus
    case minus
    case must
    case division
    case multiplication
    }
    And then use it with switch case ;)

  • @thedrei24
    @thedrei24 6 років тому

    yeah, want more algo videos like this one

  • @kennygrandberry8590
    @kennygrandberry8590 7 років тому +2

    This was amazing!! Could you cover linklist, and Dictionary algorithms. I am currently going through cracking the coding interview book, and a couple of resources to learn algorithms. Its nice to finally see someone cover algorithms in swift without trying to convert the answers from Java, or C to swift.

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому +1

      I need to get my hands on that book to get a better idea on what kind of useful algorithms are covered. I feel like Swift is a very new language and I would like to cover more relevant iOS type of challenges.

    • @kennygrandberry8590
      @kennygrandberry8590 7 років тому

      Yea its pretty good it covers some of the basic algorithms(and some really hard ones), but I am not sure what kind you may have ran into during interviews. Its really hard for me to study for them because you may run into any type of problem, so I have to be good at all the datastructures. But your vids are helping alot!!

  • @Seieukos
    @Seieukos 7 років тому

    Dang, this is extremely useful. In my Software Development class the AST was just introduced to us for our project to build a lexer. Thank you very much!

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому

      Excellent, AST is a very exciting problem set that allows you to understand recursion on another level.

  • @depdoprogramming2750
    @depdoprogramming2750 4 роки тому

    very nice explanation. thanks

  • @JeffKang84
    @JeffKang84 2 роки тому

    Which code editor feature puts those evaluation numbers on the right column? Thanks for the video.

  • @cesarcontreras8853
    @cesarcontreras8853 7 років тому +1

    hey, I would like to see a video about MVP pattern with Swift. Nice video tho, great job!

  • @sunnylin8587
    @sunnylin8587 8 місяців тому

    How can I transfer Abstract Syntax Tree which generated by OData to an API request parameter?

  • @ypaut
    @ypaut 6 років тому +1

    Greetings, what is the editor you are using? Thank you for the video.

  • @JayJay-ki4mi
    @JayJay-ki4mi 2 місяці тому

    I'm having a similar problem parsing GraphQL's AST. Nested fields and arguments can be nested so deep. I learned this at University 20 years ago and forgot everything 😓

  • @rogerwprice
    @rogerwprice 7 років тому

    Wow. Really nice. Thanks. Roger

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому +1

      Hopefully this algorithm wasn't too difficult to follow. It's a pretty common problem set CS students go over and often a similar version of this problem is given during interviews. Hope you had fun with it Roger.

  • @StunnerAlpha
    @StunnerAlpha 7 років тому

    Nice video but I have a question: Did you forget to handle the case of PEMDAS? (multiplication being processed before addition in the given example) The way you solved it would incorrectly solve the initial problem like so: 5 + 25 * 6 = 180 instead of the correct value of 155. Or am I mistaken?

  • @engen511
    @engen511 7 років тому

    Hi Brian, Are you planing to cover all the data structure and algorithms on friday episode?

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому

      Well, what kind of data structures/algorithms would you like to see?

    • @engen511
      @engen511 7 років тому

      well, i dont kow how to put this, like data structure inplementaion on
      App such Firebase chat where user can update their details on app like
      name, email address, or profile image from seetings.

  • @gozlanjeremy9951
    @gozlanjeremy9951 7 років тому

    hey Brian ! amazing videos , I have one big problem I cannot solve. I just added a button into a collection view cell, however my button is not clickable as well as not receiving actions even if I set him with a special action using add target , any clue?? he is not clickable at all!

  • @christophebugnon5155
    @christophebugnon5155 5 років тому

    You are my hero ! 😃

  • @huslerbling
    @huslerbling 7 років тому

    gave it a thumbs up and subscribed.

  • @geomichelon
    @geomichelon 7 років тому

    man..you are the best...i m watching all your videos in one wekeend .I m from Brazil and here is Carnival and i hate Carnival :-).Better pratice swift with you man... Do you think in create any tutorial with Core Data or Realm?

  • @sillygwyn
    @sillygwyn 7 років тому +1

    func evaluate(tree: Node) -> Double{
    var leftNumber = 0.0
    var rightNumber = 0.0
    if tree.rightChild == nil && tree.leftChild == nil{
    return (tree.value)!
    }
    if tree.leftChild != nil{
    leftNumber = evaluate(tree: tree.leftChild!)
    }
    if tree.rightChild != nil{
    rightNumber = evaluate(tree: tree.rightChild!)
    }
    switch (tree.operation!){
    case "+": return leftNumber + rightNumber
    case "-": return leftNumber - rightNumber
    case "*": return leftNumber * rightNumber
    default:
    if rightNumber == 0{
    print("error")
    exit(1)
    }
    else {
    return leftNumber / rightNumber
    }
    }
    }
    Not sure if this is a professional way in writing codes, but I would like to get a feedback if possible?

  • @stonelax
    @stonelax 7 років тому

    Hey Brian! We just deployed a new iOS app but we got many crashes related to parsing special characters. How can we best de-bug deployed apps? Any services you recommend? Using the built in crashlogs wasn't too useful because it only shows the function that crashed, without telling us which special characters actually caused the failure. :/

  • @rafaelrincon3109
    @rafaelrincon3109 7 років тому

    @3:40 that sounds like a challenge ;)

  • @glennmarkabalos6657
    @glennmarkabalos6657 6 років тому

    thank you for this but I have a question; how to implement the order of operation (mdas)?

    • @flutterwind7686
      @flutterwind7686 5 років тому

      This example was just about evaluating the tree, not making it. Making an AST is even more difficult. To put it simply you need to know a little about Finite Automata(ua-cam.com/video/RjOCRYdg8BY/v-deo.html) and Compiler Design. There are many algorithms to create an AST Tree, most popular is Recursive Descent Parsing(ua-cam.com/video/eVwl0hkI21Y/v-deo.html). In the Recursive Descent Algorithm, you can specify rules for operations. These are the basics in Compiling code and Programming language design.

  • @donpaulpm
    @donpaulpm 7 років тому

    🙂 how will I build my own calender with collection view...
    u should have 1 day for giving working ideas like above..😀 on our questions..too...
    it will be great... to see ans from u ...
    so I can avoid librarys as much as possible...

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому

      Can you tell me your implementation of the calendar? I'm curious what you've attempted.

    • @donpaulpm
      @donpaulpm 7 років тому

      Lets Build That App 🙄 I just implement calendar with fscalendar... But it have some issues with almofire... it shows 4error . But so far I can run the app with this red error...But I don't know if it will course any issues when I pull to app store..So I planing to have my own calender... But no idea where to start..If u pull the starting idea I will be great..or eg twice a week we all together can create custom class file for such things like discussion session.

  • @thrb41
    @thrb41 7 років тому

    Thanks!

  • @jdetnat
    @jdetnat 6 років тому

    Gracias!!! tytyty

  • @Gavolak
    @Gavolak 7 років тому +1

    In Java, I pumped out an answer in 10 minutes. But in this... I can't even name this language. Is it a variant of C? In your opinion, is Java becoming obsolete? I'm only in tenth grade and my experience is my AP computer science class, so forgive me if my knowledge Is lacking!

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому

      This is Swift, a language that is meant to replace Objective C for iOS development. Java will never be obsolete in the corporate world.

    • @robertcharmers3264
      @robertcharmers3264 7 років тому +1

      I'll second that!!! Been programming for as long as I can remember (circa 18 years). As you can imagine I have written code in numerous languages in that time from low-level Assembly to high-level Visual Basic and I'm yet to come across a language that has the shear expressiveness,flexibility and power of Java. The fact that I can write a piece of logic ONCE and deploy it as part of a Windows/Mac Desktop App, A Web Server App, Android Tablet or Mobile Phone App WITHOUT any platform-specific recompilation perfectly illustrates this point.
      Its not so much the Java language (and associated syntax and semantics) that was a breakthrough all those years ago, but rather the Language Runtime Paradigm that underpins it. The idea that perhaps, if virtualised, the entire runtime could be ported to different platforms thereby abstracting away and negating the need for developers to target said platforms themselves; developers can essentially write platform agnostic code.

  • @jincat3057
    @jincat3057 7 років тому +1

    Great lecture Brian! Easy to understand your recursion. Could you please include some solution about linkedList in the future? Since swift has no 'pointer' like C++ does, sometimes it is easy to get confused on how to get reference of an object in Swift, such as this problem in leetcode: leetcode.com/problems/min-stack/
    Thank you so much! Looking forward to next Friday.

  • @MuhammadAli-zv5vz
    @MuhammadAli-zv5vz 7 років тому

    Nice

  • @JonathanGreenwalton21
    @JonathanGreenwalton21 7 років тому +5

    Its such bullshit that interviewers force this garbage on people. I literally told my interviewer that "I'm a developer not a computer scientist we won't use this to build any apps for the company, look at my repos on github I know how to build iOS apps so ask me a real question" I've been working there since June of last year.

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому

      +Jonathan Green yeah it's unfortunate that developers are tested on unrelated algorithms during interviews that don't really gauge their competence in building complete projects. I think you did the right thing.

    • @robertcharmers3264
      @robertcharmers3264 7 років тому +1

      @Jonathan Green Still, learning a little Data Structures and Algorithm theory can't hurt can it? Personally speaking, I have always been fascinated with the topic (Data Structures and Algorithms) and remember thoroughly enjoying learning how to store and perform operations on data in the most efficient manner possible.
      Plus there *are* certain computer science specific algorithms and techniques that are vital to any application development, Recursion being principal among them. I use recursion in my day-to-day programming almost as much as iteration!! An incredibly common recursion use case my be where your App creates a number of nested folders and there is a requirement to delete the root folder and all nested folders contained within it.

    • @alb12345672
      @alb12345672 7 років тому

      Better this than some math brain teaser algo under time pressure.

  • @_slier
    @_slier 4 роки тому

    shit! ( unwrap the shit ) i will never be able to create my own compiler..building the tree itself is confusing let alone traversing it..

  • @albertlu8407
    @albertlu8407 7 років тому

    驚為天人 :D

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому +1

      还行还行 今天的影片说实话不容易录

    • @albertlu8407
      @albertlu8407 7 років тому

      It's not easy, but we have faith in you!
      👊

    • @LetsBuildThatApp
      @LetsBuildThatApp  7 років тому +1

      谢谢 I think I will go over an easier algorithm next Friday.