Is there a constructor for Dictionary in F# (that takes a Seq/List as input, and output a Dictionary)? I have written the following code that does what I want, but I am just curious maybe it is already implemented (and so I don't need to implement it myself)
let DictionaryBuilder (keyFunc:'a->'b) (valueFunc:'a->'c) aList =
let dict = new Dictionary<'b,'c>()
aList
|> Seq.iter (fun a -> dict.Add(keyFunc a, valueFunc a ))
dict // return
I know that in C#, you can use .ToDictionary (using System.Linq)
// using System.Collections.Generic;
// using System.Linq;
List<string> example = new List<string> {"a","b","c"};
Dictionary<string,string> output = example.ToDictionary(x => x+"Key", x => x+"Value");
// Output: {"aKey": "aValue", "bKey": "bValue", "cKey": "cValue"}
Thank you very much.
The signature of the dict function it's as follows:
dict : seq<'Key * 'Value> -> IDictionary<'Key,'Value>
So it takes a key value sequence as input. The key here would be to give it a key value sequence. In your case, you could use map instead of iter. The lines of code will be similar but it's a more functional way.
aList
|> Seq.map (fun a -> keyFunc a, valueFunc a )
|> dict
Edit
As TheQuickBrownFox have noted in the comments, the dict function produces a read-only dictionary.
I would recommend that you just use LINQ:
open System.Linq
[1; 2; 3].ToDictionary(id, (*) 2)
Either use it directly or use it in your helper function if you'd rather use a function than an extension method.
module Seq =
open System.Linq
let toDictionary (f:'s -> 'k) (g:'s -> 'v) (xs:_ seq) = xs.ToDictionary(f, g)
Related
I need to find a way to convert list of arbitrary values to another list
AutoMapper works if destination type is ICollection<> because it's creating an instance and populating it with Add, but my type is immutable list 'a list
So if I create list of ints:
let ints = [1; 2; 3]
And try to map it to ResizeArray<int64> (synonym to List<T>) with
mapper.Map<ResizeArray<int64>>(ints)
it will work, but if I try to map it to int64 list with
mapper.Map<int64 list>
then it will fail.
I've found a solution that will convert successfully, but it will work only with explicitly defined types
let cfg = MapperConfiguration(
fun c ->
c.CreateMap<int, int64>() |> ignore
c.CreateMap<int list, int64 list>()
.ConvertUsing(
fun source _ (cfg: ResolutionContext) ->
source
|> Seq.map cfg.Mapper.Map<int, int64>
|> Seq.toList))
So question is: How to write type converter that will convert 'a list to 'b list without explicitly defining all possible combinations of these types?
I've finally found solution. All I needed is to look at source code of this ReadOnlyCollection mapper
Solution is not perfect, because collection items transformed and inserted into System.Collections.Generic.List and afterwards converted to Microsoft.FSharp.Collections.FSharpList, which have some overhead. But at least it's working
using System.Collections.Generic;
using System.Linq.Expressions;
using static System.Linq.Expressions.Expression;
using AutoMapper.Mappers;
using AutoMapper.Internal;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;
using Microsoft.FSharp.Collections;
public class SeqToFSharpListMapper : EnumerableMapperBase
{
public override bool IsMatch(TypePair context)
=> context.SourceType.IsEnumerableType()
&& context.DestinationType.FullName.StartsWith("Microsoft.FSharp.Collections.FSharpList`1");
public override Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, IMemberMap memberMap,
Expression sourceExpression, Expression destExpression, Expression contextExpression)
{
var listType = typeof(List<>).MakeGenericType(ElementTypeHelper.GetElementType(destExpression.Type));
var list = MapCollectionExpression(configurationProvider, profileMap, memberMap, sourceExpression, Default(listType), contextExpression, typeof(List<>), MapItemExpr);
return Call(typeof(ListModule).GetMethod(nameof(ListModule.OfSeq)).MakeGenericMethod(destExpression.Type.GenericTypeArguments[0]), list);
}
}
And F#
override _.MapExpression (configurationProvider, profileMap, memberMap, sourceExpression, destExpression, contextExpression) =
let listType = typedefof<System.Collections.Generic.List<_>>.MakeGenericType(ElementTypeHelper.GetElementType destExpression.Type)
let list = MapCollectionExpression(configurationProvider, profileMap, memberMap,
sourceExpression, Default(listType), contextExpression,
typedefof<System.Collections.Generic.List<_>>,
MapItem(fun c p s d ctx i -> MapItemExpr(c, p, s, d, ctx, &i))) // compiler require explicit lambda
upcast Call(typedefof<obj list>.Assembly // don't want to use AssemblyQualifiedName
.GetType("Microsoft.FSharp.Collections.ListModule") // have to use this trick because we can't access ListModule through typeof
.GetMethod("OfSeq")
.MakeGenericMethod(destExpression.Type.GenericTypeArguments.[0]),
list)
I'm trying to build a dynamic type/class builder for C# using F#, from the following XML
<config target="string">
<protocol>string</protocol>
<about_path>string</about_path>
<about_content>
<name_path>string</name_path>
<id_path>string</id_path>
<version_path>string</version_path>
</about_content>
</config>
Using the code below I can parse the sample just fine
module XmlParser =
open FSharp.Data
open System.Globalization
open FSharp.Data.Runtime.BaseTypes
open System.Xml.Linq
[<Literal>]
let targetSchema = "<config target=\"string\">
<protocol>string</protocol>
<about_path>string</about_path>
<about_content>
<name_path>string</name_path>
<id_path>string</id_path>
<version_path>string</version_path>
</about_content>
</config>"
type Configuration = XmlProvider<targetSchema>
The problem now is that I can't get my head around retrieving the inner parts of the about_content tag.
After parsing the actual xml using
let parsedValue = Configuration.Parse(xmlIn)
I've tried to get my head around the recursion handling in F# but am stuck at the non-working code that looks like this (e would be parsedValue.XElement)
let rec flatten ( e : System.Xml.Linq.XElement) (out:List<string>) =
if e.HasElements
then for inner in e.Elements -> flatten(inner)
else e.Name.LocalName
What I would need is a hint on how to gather the e.Name.LocalName values into a sequence/List as a result of the recursion. I could also live with having a list of XElements at the end.
The function flatten needs to return a sequence, not a single thing.
For elements with subelements, you need to call flatten for each, then concat all results:
e.Elements() |> Seq.map flatten |> Seq.concat
(note that XElement.Elements is a method, not a property; therefore, you need to add () to call it)
For a single element, just return its name wrapped in a single-element sequence:
Seq.singleton e.Name.LocalName
Putting it all together:
let rec flatten (e : System.Xml.Linq.XElement) =
if e.HasElements
then e.Elements() |> Seq.map flatten |> Seq.concat
else Seq.singleton e.Name.LocalName
(also note that I have removed your out parameter, which, I assume, was meant to be not a parameter, but an attempt to declare the function's return type; it can be omitted; for reference, function return type in F# is declared after the function's signature with a colon, e.g. let f (x:int) : int = x + 5)
If you prefer a more imperative-looking style, you can use the seq computation expression. yield will yield a single element, while yield! will have the effect of yielding each element of another sequence:
let rec flatten (e : System.Xml.Linq.XElement) =
seq {
if e.HasElements then
for i in e.Elements() do
yield! flatten i
else
yield e.Name.LocalName
}
How can I create a function called getFuncName that takes a function of type (unit -> 'a) and returns its name.
I was talking to one of the C# devs and they said you could use the .Method property on a Func type as shown in an example here.
I tried to convert this to F# :
for example convert (unit -> 'a) to a type Func<_> then call the property on it but it always returns the string "Invoke".
let getFuncName f =
let fFunc = System.Func<_>(fun _ -> f())
fFunc.Method.Name
let customFunc() = 1.0
// Returns "Invoke" but I want it to return "customFunc"
getFuncName customFunc
A bit of background to this problem is:
I have created an array of functions of type (unit -> Deedle.Frame). I now want to cycle through those functions invoking them and saving them to csv with the csv name having the same name as the function. Some hypothetical code is below:
let generators : (unit -> Frame<int, string>) array = ...
generators
|> Array.iter (fun generator -> generator().SaveCsv(sprintf "%s\%s.csv" __SOURCE_DIRECTORY__ (getFuncName generator)))
This is being used in a scripting sense rather than as application code.
Not sure how you searched for information, but the first query to the search engine gave me this response:
let getFuncName f =
let type' = f.GetType()
let method' = type'.GetMethods() |> Array.find (fun m -> m.Name="Invoke")
let il = method'.GetMethodBody().GetILAsByteArray()
let methodCodes = [byte OpCodes.Call.Value;byte OpCodes.Callvirt.Value]
let position = il |> Array.findIndex(fun x -> methodCodes |> List.exists ((=)x))
let metadataToken = BitConverter.ToInt32(il, position+1)
let actualMethod = type'.Module.ResolveMethod metadataToken
actualMethod.Name
Unfortunately, this code only works when F# compiler does not inline function body into calling method.
Taken from here
Although there may be a more simple way.
I'm a beginner in F# and I'm trying to write a function to subset a dictionary given list, and return the result.
I tried this, but it doesn't work.
let Subset (dict:Dictionary<'T,'U>) (sub_list:list<'T>) =
let z = dict.Clear
sub_list |> List.filter (fun k -> dict.ContainsKey k)
|> List.map (fun k -> (k, dict.TryGetValue k) )
|> List.iter (fun s -> z.Add s)
|> List.iter (fun s -> z.Add s);;
--------------------------------------^^^
stdin(597,39): error FS0039: The field, constructor or member 'Add' is not defined
Perhaps there is a native function in F# to do that ?
thanks
EDIT
thanks to #TheInnerLight for his answer below
can you just educate me a bit more, and tell me how i should adapt that function if i want to return the original variable being modified ?
(of course it would be possible to go from where we call that function, call it with a temp variable, and reassign)
You have written:
let z = dict.Clear
z is of type unit->unit yet you are calling z.Add.
I suspect you want to write
let subset (dict:Dictionary<'T,'U>) (sub_list:list<'T>) =
let z = Dictionary<'T,'U>() // create new empty dictionary
sub_list |> List.filter (fun k -> dict.ContainsKey k)
|> List.map (fun k -> (k, dict.[k]) )
|> List.iter (fun s -> z.Add s)
z
TryGetValue is going to return something of type bool*'U in F#, which I suspect you don't want if already filtering by ContainsKey so you probably want to look up directly with dict.[k].
Note that Dictionary is a mutable collection so if you were to actually call dict.Clear(), it wouldn't return a new empty dictionary, it would mutate the existing one by clearing all elements. The immutable F# data structure usually used for key-value relationships is Map, see https://msdn.microsoft.com/en-us/library/ee353880.aspx for things you can do with Map.
Here is a map version (this is the solution I recommend):
let subset map subList =
subList
|> List.choose (fun k -> Option.map (fun v -> k,v) (Map.tryFind k map))
|> Map.ofList
Edit (in response to the question edit about modifying the input variable):
It's possible to update an existing dictionary using the destructive update operator <- on a mutable variable.
Option 1:
let mutable dict = Dictionary<Key,Value>() // replace this with initial dictionary
let lst = [] // list to check against
dict <- sublist dict lst
Likewise, my first function could be changed to perform only a side effect (removing unwanted elements).
Option 2:
let subset (d : System.Collections.Generic.Dictionary<'T,'U>) (sub_list : list<'T>) =
sub_list
|> List.filter (d.ContainsKey >> not)
|> List.iter (d.Remove >> ignore)
For an F# beginner I don't really recommend Option 1 and I really don't recommend Option 2.
The functional approach is to favour immutable values, pure functions, etc. This means you will be better off thinking of your functions as defining data transformations rather than as defining a list of instructions to be performed.
Because F# is a multi-paradigm language, it's easy to fall back on the imperative in the early stages but you will probably gain the most from learning your new language if you force yourself to adopt the standard paradigm and idioms of that language even if those idioms feel strange and uncomfortable to begin with.
The immutable data structures like Map and list are pretty efficient at sharing data as well as providing good time complexity so these are really the go-to collections when working in F#.
The following type extension
module Dict =
open System.Collections.Generic
type Dictionary<'K, 'V> with
member this.Difference(that:Dictionary<'K, 'T>) =
let dict = Dictionary()
for KeyValue(k, v) in this do
if not (that.ContainsKey(k)) then
dict.Add(k, v)
dict
gives the error:
The signature and implementation are not compatible because the declaration of the type parameter 'TKey' requires a constraint of the form 'TKey : equality
But when I add the constraint it gives the error:
The declared type parameters for this type extension do not match the declared type parameters on the original type 'Dictionary<,>'
This is especially mysterious because the following type extension doesn't have the constraint and works.
type Dictionary<'K, 'V> with
member this.TryGet(key) =
match this.TryGetValue(key) with
| true, v -> Some v
| _ -> None
Now I'm having weird thoughts: is the constraint required only when certain members are accessed?
module Dict =
open System.Collections.Generic
type Dictionary<'K, 'V> with
member this.Difference(that:Dictionary<'K, 'T>) =
let dict = Dictionary(this.Comparer)
for KeyValue(k, v) in this do
if not (that.ContainsKey(k)) then
dict.Add(k, v)
dict
EDIT:
As per F# spec (14.11 Additional Constraints on CLI Methods)
Some specific CLI methods and types are treated specially by F#, because they are common in F# programming and cause extremely difficult-to-find bugs. For each use of the following constructs, the F# compiler imposes additional ad hoc constraints:
x.Equals(yobj) requires type ty : equality for the static type of x
x.GetHashCode() requires type ty : equality for the static type of x
new Dictionary<A,B>() requires A : equality, for any overload that does not take an IEqualityComparer<T>
as far as I can see the following code does the trick:
module Dict =
open System.Collections.Generic
type Dictionary<'K, 'V> with
member this.Difference(that: Dictionary<'K,'V2>) =
let diff =
this
|> Seq.filter (fun x -> not <| that.ContainsKey(x.Key))
|> Seq.map (fun x -> x.Key, x.Value)
System.Linq.Enumerable.ToDictionary(diff, fst, snd)
The problem is your use of the Add method. If you use this method of Dictionary<TKey, TValue> then F# will enforce that TKey has the equality constraint.
After playing around a bit I'm not sure that it's even possible to write this extension method. The F# type system appears to force the declaration type of the extension method to have no additional constraints than the original type (i get an error whenever I add the equality constraint). Additionally the type listed in the individal extension methods cannot differ than the listed type. I've tried a number of ways and can't get this to function correctly.
The closest I've come is the non-extension method as follows
let Difference (this : Dictionary<'K, 'T>) (that:Dictionary<'K, 'T> when 'K : equality) =
let dict = Dictionary()
for KeyValue(k, v) in this do
if not (that.ContainsKey(k)) then
dict.Add(k, v)
dict
Perhaps another F# ninja will be able to prove me wrong
(EDIT: CKoenig has a nice answer.)
Hm, I didn't immediately see a way to do this either.
Here's a non-type-safe solution that might provide some crazy inspiration for others.
open System.Collections.Generic
module Dict =
type Dictionary<'K, 'V> with
member this.Difference<'K2, 'T when 'K2 : equality>(that:Dictionary<'K2, 'T>) =
let dict = Dictionary<'K2,'V>()
for KeyValue(k, v) in this do
if not (that.ContainsKey(k |> box |> unbox)) then
dict.Add(k |> box |> unbox, v)
dict
open Dict
let d1 = Dictionary()
d1.Add(1, "foo")
d1.Add(2, "bar")
let d2 = Dictionary()
d2.Add(1, "cheese")
let show (d:Dictionary<_,_>) =
for (KeyValue(k,v)) in d do
printfn "%A: %A" k v
d1.Difference(d2) |> show
let d3 = Dictionary()
d3.Add(1, 42)
d1.Difference(d3) |> show
let d4 = Dictionary()
d4.Add("uh-oh", 42)
d1.Difference(d4) |> show // blows up at runtime
Overall it seems like there may be no way to unify the types K and K2 without also forcing them to have the same equality constraint though...
(EDIT: seems like calling into .NET which is equality-constraint-agnostic is a good way to create a dictionary in the absence of the extra constraint.)