Coder Social home page Coder Social logo

drunken-octo-bear's People

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

drunken-octo-bear's Issues

Chapter 3

Wrapping Core Image: Providing a solid example.

The chapter explains that like in real life you don't live in a totally functional world, and aims to provide an actual example where they take a known API, and provide a functional wrapper. IMO this is a lot of the type of functional programming I've seen ( RAC, Moya etc. ). The plan is to take a stringly typed API like Core Image ( lots of magic strings in the API ) and to provide not just a better version of the CIFilter class, but a way of uniquely composing them.

Like with the earlier chapters, typealising your function upfront gives be strongest functional foundations. For this they will be defining Filter as CIImage -> CIImage, so a filter is really just a function that maps an image to another image. They make an init function that makes it easy to create a CIFilter with a name and a Dictionary for its internal params.

The initial example is a blur Filter. It is a function that returns a function that takes an image, creates a CIFilter with the blur settings and runs it on the image initially passed in.

There's another example Filter that generates a colored image, this uses a feature of swift to declare a param uninteresting using the _ name.

And a third in a image composite Filter. It takes an overlay image as a parameter and it returns a function which takes an image, crops it according to the image that is in the outer function and then applies a CIFilter compositing the two.

With some working functions they then go on to talk about a composable Filter. The coloredOverlay function. This if a function that takes a color, and returns a function that:

  • takes in an CIImage (like all Filter functions)
  • generates a overlay CIImage of a single color via the coloredImage filter ( and then applying it directly with the outer color)
  • takes the result of ^ and applies the composite function directly with the returned image.

They then give an example of doing something similar composing the a blur, and an overlay. Then show how to one-liner it. It's pretty unreadable. So how do you fix that? you guessed it, more functions.

So they make a function that is a Filter composition function, it returns a Filter function that runs one Filter, then runs the output of that through another Filter. Given that this is going to be pretty common, it is then turned into a custom operator. So you can write let bgImageFilter = blur(5) >>> colorOverlay(UIColor.red). Looks much nicer, and shows what's happening well.

Currying

The chapter finishes up on Currying. A term used often later on, and worth thinking about. The key to Curring seems to be: when you have a function that takes multiple paramters you can split that up into composable functions that eventually only take one parameter incrementally.

There seems to be some special syntax in swift around this, by using multiple paramater tuples in the function definition. E.g.

func add(x:Int)(y:Int) -> Int {
  return x + y
}

add(1)(y:2)
> 3

I didn't entirely get explaination of why it is better alas after a few re-reads. So I'm not going to try explain that till I can give it a good shot.

Chapter 4 - Higher Order Functions

Chapter 4 - Higher Order Functions

Map, Filter, Reduce
Chapter starts by introducing higher order functions. In general these are a collection of pretty new functions for me, I’ve got a pretty solid grasp of these already thanks to the influence of other developers at Artsy this year.

Map

However, it’s not going to be that easy. There’s generics involved eventually. They start off with an example of a function that adds a collection of Ints together within an array using a for loop. Then they move on to doing something very similar, but that it doubles the Ints. They correctly assert there’s solid duplication between the functions, and create a function that takes a block to do the “work” for said functions. Thus creating a base for what will become the map function, but that only takes an array of Ints and returns an Int.

They then start looking at another function, but that instead of returning an Int returns a Bool. Same code as the above function but a tiny change in the function definition. They then ask do they have to define higher order functions like this for all the types if they want complier side type safety?

So they introduce Generics as a concept for swapping types. Or I guess, treating the type as a variable within the method. The interesting quotes:

To understand [these] type signatures it may help you to think of genericComputerArray<U> as a family of functions. Each choice of the type U represents a new function.

This function takes an array of Ints and a function of type Int -> U as arguments and returns an array of type [U]

They then generalise out the Int from the function turning it into a U and thereby giving what I presume is the official map function for swift.

It’s cool, if you stop reading the book here. You’ve already got a really useful new tool in your box. I use map everywhere.

Filter

They fly through one example, because the foundations of filter are pretty much the same as map. They want to search an array for things that only have a prefix of “.swift” and so create a for loop and only add things if that is true. They then abstract the loop code and the checking into a block. Then add Generics to remove the forced types.

Then they say that like with map, filter is already in the standard Swift API on an array. They then ask a question I’ve never asked myself.

Is there an even more general purpose function that could be used for both map and reduce?

They say there is. I’m excited.

Reduce

They start by making a sum function. It’s a for loop with a result += item. Then another for a product function, which is just result *= item. And a few more examples of similar ilk.

They then take a look at the commonalities: result var and a loop. Knowing this they create a generic version of reduce. It is a function that takes an array, an initial value and a block to run on each item with both the array’s item and the initial value as it changes.

It’s pretty generic-y. Lots of A and Rs. The choice of letters I presume are similar to the i,j,k things that are used in loops culturally. But the choices don’t have a similar pattern of escalation.

Luckily they explain the function well:

It’s generic in two ways: for any input array of type [A] it will compute a result R. To do this it need an initial object of type R ( to assign to the results variable ) and a function combine(R,A) -> R which is used to update the result variable.

They then code-golf some functions down using swift syntax elegantly. And go as far as to reproduce map and filter using reduce. I wasn’t expecting that actually. 👍 - nice surprise.

They then go through some examples of using map, filter and reduce with some pretty common code and it looks cool. They then bring up the AnyObject concept.

They explain that whilst the AnyObject can be used instead of a generic ( as would be done in objc. ) Doing so would remove the compiler from the equation as it would lose the type information.

They give some examples of AnyObject vs generic functions and show how you can break the function method declaration promise with an AnyObject but that you can’t not return what you’d say you would with a generic. Which means less bugs.

—-

They wrap up with they example from Wrapping Core Image earlier. Which I’m kind of struggling with describing. I’ll come back to this in a comment tomorrow morning.

outline the format for how this works

Probably, from talking, one of us writes a chapter with some homework, the other responds.

What happens next could be interesting. If I write a summary and add some exercises that you respond to, I could then critique those, or provide a solution of my own.

Chapters 1 & 2

C1 : Introduction

Given that there's no code in here, there's no exercises. It's interesting from the perspective of how do you pitch Functional Programming without being autological. Instead of trying to give a formal mathematical approach to functional programming they opted to highlight the qualities it embodies, notably:

  • Modularity by composition.

    Rather than thinking of a program as a seuqence of assignments and method calls, functional programmers emphasize that each program can be repeatedly broken into smaller and smaller pieves.

  • De-emphasising state.

    Functional Programming on the other hand, emphaisizse the importance of proframming with valuesm free of mutable state or other side effects.

C2 : Thinking Functionally

This chapter aims to showcase building some imperitve code, and then starts to turn it into function components. They build up a single function inRange for determining whether a battleship's can shoot something in range (will I hit myself, is it too far, etc).

The first thing they do is define a typealias for the type of function they want: typealias Region = Position -> Bool. This means syntactically that whenever they think of a region they're really talking about:

Instead of defining an object of struct to represent regions, we represent a region by a function that determines if a given point is in the region or not. If you're not used to functional programming, this may seem strange.

They're right. It does. They then go into the reasoning for it, and for the name..

These names suggest that they denote a function type, yet the key philosophy underlying functional programming is that functions are values, no different from structs, integers or booleans. Using a separate naming convention for functions would violate this philosophy.

They then start splitting the original method up by giving examples of functions that conform to Region

function What it takes What it returns
circle (radius) Takes a radius A function that returns if the point passed to said function is inside a circle of that radius.

They then explore improving the circle method to add a position for the circle, but backtrack on it. Explaining that a more functional approach would be to write a generic region transformer.

function What it takes What it returns
shift (offset, region) Takes an offest and a Region function It makes a new Postition by offsetting the original by x and y, then returns the region function with the new Position.

This is one of the core concepts of functional programming: rather than creating increasingly complicated functions such as circle two, we have written a function shift which modifies another function.

They then finish up the rest of the functions required to have a functional version of inRange.

function What it takes What it returns
invert (region) Takes a Region function A function that calls the region function then does a ! on it to swich the return value.
intersection (region, region2) Takes 2 Region functions A function that &&s the two region functions.
union (region, region2) Takes 2 Region functions A function that `
difference (region, region2) Takes 2 Region functions A function that intersectionss the first plus the invert of the 2nd region function.

Instead of writing complex functions to solve a specific progrlem we can now use many small functions that can be assembled to solve a wide variety of problems.

They then discuss the upsides / downsides of this approach. One of the oddities here, and I struggled to explain this verbally is that as a region is a function, there is no way to specifically look at what the function is. There is no state that says "square" just a function like square(length) that you would have to run many times ( they mention to visualise you would have to generate a bitmap of whther Positions hit it or not. ) This was a problem that I found with Reactive Cocoa a lot.

They finish up by talking about how spending time upfront thinking about your types will guides your development process the most here.


So I found my run through of this chapter a pretty solid intro. I'm glad they included the point that the example was inspired by a haskell example, didn't like the militery-ness of it. By writing out the tables above I started to really feel like I had a grip on the idea that everything really is returning a function, but that each function we were creating was modifying another one slightly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.