Reputation: 27
I'd like to know how to convert this code line by line from C# to F#. I am not looking to use any kind of F#'s idioms or something of the like. I am trying to understand how to enumaration and reflcetion in F#.
using System.Linq;
namespace System.Collections.Generic
{
public static class EnumerableExtensions
{
private static readonly Random random;
static EnumerableExtensions()
{
random = new Random();
}
public static T Random<T>(this IEnumerable<T> input)
{
return input.ElementAt(random.Next(input.Count()));
}
}
}
Upvotes: 0
Views: 48
Reputation: 243116
You can define extensions as static methods in a type, but you have to mark those with the Extension
attribute. A direct rewrite of your C# code would be:
open System.Runtime.CompilerServices
[<Extension>]
type EnumerableExtensions() =
static let rnd = System.Random()
[<Extension>]
static member Random(input:seq<_>) =
input |> Seq.item (rnd.Next(Seq.length input))
[1;2;3].Random()
Upvotes: 1