Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In F# this is approximated with:

  type 'a IEnumerable with
    member this.filterMap f = 
       [for x in this do if f x <> None then yield (f x).Value]

  let j =  Map([("a",1) ; ("b",2) ]).filterMap(fun kv -> if kv.Value = 1 then Some(kv.Key,kv.Value) else None) |> Map.ofList

  let n = [1.;2.;4.].filterMap(fun x -> if x % 2. = 0. then Some(x**2.) else None) 
The extension works with any Sequence (arrays, sequences, maps,etc.) with the caveat that it maps every enumerable to a list. You could also define an extension for a specific type where a broad definition does not make sense.

Personally, I lean more functional, I have never run across a need for extending things in this manner.



Arrays are not sequences in Scala. They are Java arrays, not Scala sequences.


Yes, I picked this up, and was not making any statement against that. In fact I do not subscribe to the validity of his approach. But I gave a shot at seeing if I could give code that was succinct and matched.

The requirement was to add a method that works for all collections, whether platform or language specific, while preserving type. The code I gave is an approximation of a solution - to use a rough analogy: topologically speaking the code matches but loses the geometry. The code I gave works on basically all .NET collections, whether C# or F#, string or tree - as long as they implement the interface - they are matched. That it leverages the existing organization should not count against it. The failing is that although types are preserved it is under a new geometry or structure.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: