Skip to content

Instantly share code, notes, and snippets.

@Nadohs
Last active December 30, 2015 07:09
Show Gist options
  • Save Nadohs/efe3b136b3e59765c667 to your computer and use it in GitHub Desktop.
Save Nadohs/efe3b136b3e59765c667 to your computer and use it in GitHub Desktop.
curried function with generics...
private func comparableAttributes<T, U:Equatable>(first f:T, second s:T)->(T->U) -> U?{
    return { trans in
        let x = trans(f)
        let y = trans(s)
        return (x == y) ? nil : x
    }
}

If i do this it doesnt work...

let comparitor = comparableAttributes(first: paragraph, second: defaultParagraph)

error:cannot invoke 'comparableAttributes with argument list of type(first:NSParagraphStyle, second:NSParagraphStyle)`*

this is what I want to do

let comparitor = comparableAttributes(first: paragraph, second: defaultParagraph)

self.headIndent = comparitor{$0.headIndent}
self.tailIndent = comparitor{$0.tailIndent}

to replace this..

//self.headIndent = (paragraph.headIndent == defaultParagraph.headIndent) ? nil : Float(paragraph.headIndent)
//self.tailIndent = (paragraph.tailIndent == defaultParagraph.tailIndent) ? nil : Float(paragraph.tailIndent)

I CAN do this:

let comparitor = comparableAttributes(first: paragraph, second: defaultParagraph)({ $0.alignment })

It appears that the curried function needs to establish all of the generic types in the first set of function parameters.

@Nadohs
Copy link
Author

Nadohs commented Dec 22, 2015

So testing this out further, the generics will work with currying if all of the generic types are established before getting to the second function. In the example above, the closure returned is not able to establish the type U. For instance a function that looks like this works fine:
func <T, U:Equatable>(T->U) -> (first f:T, second s:T) -> U?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment