How to Implement Map Function in VB.NET

此生再无相见时 提交于 2019-12-22 10:27:36

问题


I am trying to implement Map in VB.NET with the functionality described in this answer.

It should take an IEnumerable(Of TIn) and a Function(Of TIn, TOut), execute the function over every element, and return a new IEnumerable(Of TOut).

I know VB.NET is not a true functional language. I have business requirements, but would still like to use some functional tidbits, especially in conjunction with LINQ.

A similar question is asked here, but the question and answer are actually about implementing Each.


回答1:


Thanks to @Sehnsucht for pointing out that there already is a Map function in LINQ that is called Select.

Here is my original answer that is definitely not as good as what the smart people designing LINQ created:

Here is a an extension method that can be placed in a Module in the root namespace:

Module Extensions
    <System.Runtime.CompilerServices.Extension> _
    Public Function Map(Of TIn, TOut)(ByVal a As IEnumerable(Of TIn), ByVal f As Func(Of TIn, TOut)) As IList(Of TOut)
        Dim l As New List(Of TOut)
        For Each i As TIn In a
            Dim x = f(i)
            l.Add(x)
        Next
        Return l
    End Function
End Module

It can be called like:

Sub Main()
    Dim Test As New List(Of Double) From {-10000000, -1, 1, 1000000}
    Dim Result1 = Test.Map(Function(x) x.ToString("F2"))
    'Result1 is of type IList(Of String)
    Dim Result2 = Test.Map(AddressOf IsPositive)
    'Result2 is of type IList(Of Boolean)
    Dim Result3 = Map(Test, Function(y) y + 1)
    'Result3 is of type IList(Of Double)
End Sub

Private Function IsPositive(d As Double) As Boolean
    If d > 0 then
        Return True
    Else
        Return False
    End If
End Function

I return an IList(Of TOut) because it is more useful for my purposes (and, well, it's returning a list!). It could return an IEnumerable(Of TOut) by changing the return line to Return l.AsEnumerable(). It accepts an IEnumerable(Of TIn) instead of an IList(Of TIn) so it can accepts a wider range of inputs.

I'm open to anybody suggesting performance improvements.




回答2:


super simple

   Public Function map(equation As Func(Of Object, Object))

    For i = 0 To rows - 1
        For j = 0 To cols - 1
            Dim val = data(i, j)
            data(i, j) = equation(val)
        Next
    Next
End Function

and to use it

 m.map(Function(x) 3 > x)
 m.map(Address Sigmoid)


来源:https://stackoverflow.com/questions/31008744/how-to-implement-map-function-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!