swift - find() using Functional Programming -


i'd create generic find() typically used in functional programming. in functional programming don't work array indices , loops. filter. way works if have list of

["apple", "banana", "cherry"]  

and want find banana assign array indices list elements creating tuples

[(1, "apple"), (2, "banana"), (3, "cherry")]  

now can filter down "banana" , return index value.

i trying create generic function error. what's wrong syntax?

func findingenericindexedlist<t>(indexedlist: [(index: int, value: t)], element: (index: int, value: t)) -> int? {             let found = indexedlist.filter {   // error: cannot invoke 'filter' argument list of type '((_) -> _)'          element.value === $0.value     }      if let definitefound = found.first {         return definitefound.index     }     return nil } 

update 1: use above solution opposed using find() (will deprecated) or in swift 2.0 indexof() because i'm trying follow functional programming paradigm, relying on general functions , not class methods.

the minimum change required make work make t conform equatable , use == operator.

func findingenericindexedlist<t:equatable>(indexedlist: [(index: int, value: t)], element: (index: int, value: t)) -> int? {     let found = indexedlist.filter {         element.value == $0.value     }      if let definitefound = found.first {         return definitefound.index     }     return nil } 

it doesn't make sense use === here because going applying value types (especially if following functional paradigms) never true.

beyond spent time thinking problem , here do:

extension array element : equatable {     func find(element:array.generator.element) -> int? {         let indexedlist = lazy(self.enumerate())         let found = indexedlist.filter {             element == $1         }          let definitefound = found.prefix(1)         return definitefound.generate().next()?.index     } } 

protocol extension on array because makes syntax neater, lazy sequence avoid checking every element, 0 indexed.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -