F# iteration over a Dictionary - f#

I'm just starting with F# and I want to iterate over a dictionary, getting the keys and values.
So in C#, I'd put:
IDictionary resultSet = test.GetResults;
foreach (DictionaryEntry de in resultSet)
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}
I can't seem to find a way to do this in F# (not one that compiles anyway).
Could anybody please suggest the equivalent code in F#?
Cheers,
Crush

What is the type of your dictionary?
If it is non-generic IDictionary as your code snippet suggests, then try the following (In F#, for doesn't implicitly insert conversions, so you need to add Seq.cast<> to get a typed collection that you can easily work with):
for entry in dict |> Seq.cast<DictionaryEntry> do
// use 'entry.Value' and 'entry.Key' here
If you are using generic IDictionary<'K, 'V> then you don't need the call to Seq.cast (if you have any control over the library, this is better than the previous option):
for entry in dict do
// use 'entry.Value' and 'entry.Key' here
If you're using immutable F# Map<'K, 'V> type (which is the best type to use if you're writing functional code in F#) then you can use the solution by Pavel or you can use for loop together with the KeyValue active pattern like this:
for KeyValue(k, v) in dict do
// 'k' is the key, 'v' is the value
In both of the cases, you can use either for or various iter functions. If you need to perform something with side-effects then I would prefer for loop (and this is not the first answer where I am mentioning this :-)), because this is a language construct designed for this purpose. For functional processing you can use various functions like Seq.filter etc..

resultSet |> Map.iter (fun key value ->
printf "Key = %A, Value = %A\n" key value)

(This is a shorter answer than Tomas' one, going to the point.) Dictionaries are mutable, in F# it's more natural to use Maps (immutable). So if you're dealing with map: Map<K,V>, iterate through it this way:
for KeyValue(key,value) in map do
DoStuff key value

Related

Downcast using type object in F#

let o1 = box SomeType()
let t = typeof<SomeType>
Is it possible to downcast (to SomeType) a boxed object (o1) using the Type information stored in other object (o1)?
The ultimate objective is to have a sort of dynamic invocation of functions.
I'm storing functions with signature FSharpFunc<'Pre,'Post> in a Map:
// Lack of Covariance/Contravariance force me to define it as obj:
let functions = Map<string,obj>
let invoke f (pre : 'Pre when 'Pre : comparison) (post : 'Post when 'Post : comparison) =
(unbox<FSharpFunc<'Pre,'Post>> f).Invoke(pre)
This dynamic invocation works whenever I pass the proper types objects in pre and post.
And know comes the issue. I also has the arguments of the invocation in a map of the form:
let data = Map<string,obj>
let conf = Map<string, Type>
where conf stores the type of each possible string key in data.
So given a function key and a proper configuration, I can retrieve the arguments from data in order to feed the function. But for these to work I should be able to downcast data values using conf Types.
I suspect that it is not possible and I'm aware that I am bypassing static type safety (I'm ok with that). In that case, Any workaround or alternative approach?
I'm not sure I understand what you are after here, so this is not a specific answer to your question, but rather a couple of suggestions that might help you.
Generally speaking it sounds like you want some sort of existential types. It sounds like
you have data of various types and
you have operations on that data and
you want to dynamically invoke those operations on the data.
To make such things safely, you should encapsulate the data (or ideally the type of the data) and the operations together rather than separately. At the point when you know the type of the data and the possible operations on the data, wrap them together so that other parts of your program cannot just take the data and try to unsafely perform arbitrary operations on the data. (To make such encapsulation general and safe, allowing type safe manipulation of data whose type is not know statically, you need something like first-class modules.)
As another suggestion, rather than boxing whole functions, you might rather want to box and unbox
the domains and ranges of functions. Consider the following wrap and unwrap functions:
let wrap (a2b: 'a -> 'b) : obj -> obj =
unbox<'a> >> a2b >> box<'b>
let unwrap (o2o: obj -> obj) : 'a -> 'b =
box<'a> >> o2o >> unbox<'b>
The function map would have the signature
val functions: Map<string, obj -> obj>
and would store wrapped functions. To invoke a function from the map, you would unwrap the previously wrapped o2o function with the desired type:
(unwrap o2o : 'a when 'a: comparison -> 'b when 'b: comparison)
This is not type safe as such, but allows for flexible invocations.

Declaring a variable without assigning

Any way to declare a new variable in F# without assigning a value to it?
See Aidan's comment.
If you insist, you can do this:
let mutable x = Unchecked.defaultof<int>
This will assign the absolute zero value (0 for numeric types, null for reference types, struct-zero for value types).
It would be interesting to know why the author needs this in F# (simple example of intended use would suffice).
But I guess one of the common cases when you may use uninitialised variable in C# is when you call a function with out parameter:
TResult Foo<TKey, TResult>(IDictionary<TKey, TResult> dictionary, TKey key)
{
TResult value;
if (dictionary.TryGetValue(key, out value))
{
return value;
}
else
{
throw new ApplicationException("Not found");
}
}
Luckily in F# you can handle this situation using much nicer syntax:
let foo (dict : IDictionary<_,_>) key =
match dict.TryGetValue(key) with
| (true, value) -> value
| (false, _) -> raise <| ApplicationException("Not Found")
You can also use explicit field syntax:
type T =
val mutable x : int
I agree with everyone who has said "don't do it". However, if you are convinced that you are in a case where it really is necessary, you can do this:
let mutable naughty : int option = None
...then later to assign a value.
naughty <- Some(1)
But bear in mind that everyone who has said 'change your approach instead' is probably right. I code in F# full time and I've never had to declare an unassigned 'variable'.
Another point: although you say it wasn't your choice to use F#, I predict you'll soon consider yourself lucky to be using it!
F# variables are by default immutable, so you can't assign a value later. Therefore declaring them without an initial value makes them quite useless, and as such there is no mechanism to do so.
Arguably, a mutable variable declaration could be declared without an initial value and still be useful (it could acquire an initial default like C# variables do), but F#'s syntax does not support this. I would guess this is for consistency and because mutable variable slots are not idiomatic F# so there's little incentive to make special cases to support them.

Call a function from its name as a string in f#

I thought that I might be able to do this with quotations - but I can't see how.
Should I just use a table of the functions with their names - or is their a way of doing this?
Thanks.
For more info......
I'm calling a lot of f# functions from excel and I wondered if I could write a f# function
let fs_wrapper (f_name:string) (f_params:list double) =
this bit calls fname with f_params
and then use
=fs_wrapper("my_func", 3.14, 2.71)
in the sheet rather than wrap all the functions separately.
You'll need to use standard .NET Reflection to do this. Quotations aren't going to help, because they represent function calls using standard .NET MethodInfo, so you'll need to use reflection anyway. The only benefit of quotations (compared to naive reflection) is that you can compile them, which could give you better performance (but the compilation isn't perfect).
Depending on your specific scenario (e.g. where are the functions located), you'd have to do something like:
module Functions =
let sin x = sin(x)
let sqrt y = sqrt(y)
open System.Reflection
let moduleInfo =
Assembly.GetExecutingAssembly().GetTypes()
|> Seq.find (fun t -> t.Name = "Functions")
let name = "sin"
moduleInfo.GetMethod(name).Invoke(null, [| box 3.1415 |])
Unless you need some extensibility or have a large number of functions, using a dictionary containing string as a key and function value as the value may be an easier option:
let funcs =
dict [ "sin", Functions.sin;
"sqrt", Functions.sqrt ]
funcs.[name](3.1415)
There are many methods but one way is to use Reflection, for instance:
typeof<int>.GetMethod("ToString", System.Type.EmptyTypes).Invoke(1, null)
typeof<int>.GetMethod("Parse", [|typeof<string>|]).Invoke(null, [|"112"|])
GetMethod optionally takes an array of types that define the signature, but you can skip that if your method is unambiguous.
Following up on what Thomas alluded to, have a look at Using and Abusing the F# Dynamic Lookup Operator by Matthew Podwysocki. It offers a syntactically clean way for doing dynamic lookup in F#.

F# Functions vs. Values

This is a pretty simple question, and I just wanted to check that what I'm doing and how I'm interpreting the F# makes sense. If I have the statement
let printRandom =
x = MyApplication.getRandom()
printfn "%d" x
x
Instead of creating printRandom as a function, F# runs it once and then assigns it a value. So, now, when I call printRandom, instead of getting a new random value and printing it, I simply get whatever was returned the first time. I can get around this my defining it as such:
let printRandom() =
x = MyApplication.getRandom()
printfn "%d" x
x
Is this the proper way to draw this distinction between parameter-less functions and values? This seems less than ideal to me. Does it have consequences in currying, composition, etc?
The right way to look at this is that F# has no such thing as parameter-less functions. All functions have to take a parameter, but sometimes you don't care what it is, so you use () (the singleton value of type unit). You could also make a function like this:
let printRandom unused =
x = MyApplication.getRandom()
printfn "%d" x
x
or this:
let printRandom _ =
x = MyApplication.getRandom()
printfn "%d" x
x
But () is the default way to express that you don't use the parameter. It expresses that fact to the caller, because the type is unit -> int not 'a -> int; as well as to the reader, because the call site is printRandom () not printRandom "unused".
Currying and composition do in fact rely on the fact that all functions take one parameter and return one value.
The most common way to write calls with unit, by the way, is with a space, especially in the non .NET relatives of F# like Caml, SML and Haskell. That's because () is a singleton value, not a syntactic thing like it is in C#.
Your analysis is correct.
The first instance defines a value and not a function. I admit this caught me a few times when I started with F# as well. Coming from C# it seems very natural that an assignment expression which contains multiple statements must be a lambda and hence delay evaluated.
This is just not the case in F#. Statements can be almost arbitrarily nested (and it rocks for having locally scoped functions and values). Once you get comfortable with this you start to see it as an advantage as you can create functions and continuations which are inaccessible to the rest of the function.
The second approach is the standard way for creating a function which logically takes no arguments. I don't know the precise terminology the F# team would use for this declaration though (perhaps a function taking a single argument of type unit). So I can't really comment on how it would affect currying.
Is this the proper way to draw this
distinction between parameter-less
functions and values? This seems less
than ideal to me. Does it have
consequences in currying, composition,
etc?
Yes, what you describe is correct.
For what its worth, it has a very interesting consequence able to partially evaluate functions on declaration. Compare these two functions:
// val contains : string -> bool
let contains =
let people = set ["Juliet"; "Joe"; "Bob"; "Jack"]
fun person -> people.Contains(person)
// val contains2 : string -> bool
let contains2 person =
let people = set ["Juliet"; "Joe"; "Bob"; "Jack"]
people.Contains(person)
Both functions produce identical results, contains creates its people set on declaration and reuses it, whereas contains2 creates its people set everytime you call the function. End result: contains is slightly faster. So knowing the distinction here can help you write faster code.
Assignment bodies looking like function bodies have cought a few programmers unaware. You can make things even more interesting by having the assignment return a function:
let foo =
printfn "This runs at startup"
(fun () -> printfn "This runs every time you call foo ()")
I just wrote a blog post about it at http://blog.wezeku.com/2010/08/23/values-functions-and-a-bit-of-both/.

How to create a type that implement IDictionary<'K, 'V> and IEnumerable<'V>

I want to create a read-only keyed collection that implements IDictionary<'K, 'V> and IEnumerable<'V>. Taking the obvious approach I get the following error:
This type implements or inherits the same interface at different generic instantiations 'IEnumerable<'V>' and 'IEnumerable<KeyValuePair<'K,'V>>'. This is not permitted in this version of F#.
Is there a different way of achieving this?
EDIT - Since this seems to be an insurmountable limitation of F#, what would be an idiomatic way of achieving this? One thought that comes to mind is providing members that return the desired view of the data, e.g., member x.List : IList<'V> and member x.Dict : IDictionary<'K, 'V>. Object expressions could be used to provide the implementations. Any other ideas?
One relatively easy approach is to expose the implementation of the two interfaces as members of the type you are writing. This can be done quite nicely using object expressions or just by writing a piece of code that constructs some type and returns it as the result. The second approach would look like this:
type MyCollection<'K, 'V when 'K : equality>(keys:list<'K>, values:list<'V>) = //'
member x.Dictionary =
Seq.zip keys values |> dict
member x.Enumerable =
values |> List.toSeq
The first approach (if you want to implement methods of the interfaces directly would look roughly like this:
type MyCollection<'K, 'V when 'K : equality>(keys:list<'K>, values:list<'V>) = //'
member x.Dictionary =
{ new IDictionary<'K, 'V> with
member d.Add(k, v) = ... }
member x.Enumerable =
// Similarly for IEnumerable
values |> List.toSeq
Exposing the implementations as functions in a module as mentioned by kvb is also a great option - I think that many of the standard F# library types actually do both of the options (so that the user can choose the style he/she prefers). This can be added like this:
module MyCollection =
let toDict (a:MyCollection<_, _>) = a.Dictionary
I'm afraid not. The CLR allows implementation of multiple interfaces of course (even of the same base type), but not the F# language. I believe you won't have any problems if you write the class in C#, but F# is going to give you problems in the current version.
As Noldorin says, this is not possible. One idiomatic approach is to provide toSeq and toDict functions on a module with the same name as your type (like List.toSeq, Array.toSeq, etc.).

Resources