Paperprosonline - How do I apply a dictionary of functions to a dictionary in KDB? - editor

Suggestion required. How do I apply a dictionary of functions to a dictionary in KDB?
I attempted
f s
f # s

Related

Hashtable in Ocaml where key is a tuple

I am trying to construct a LL1 parse table in ocaml. I'd like for the key to be a Nonterminal, input_symbol tuple. Is this possible?
I know you can do a stack of tuples:
let (k : (string*string) Stack.t) = Stack.create ();;
Thank you in advance!!
The key of a hash table in OCaml can have any type that can be compared for equality and can be hashed to an integer. The "vanilla" interface uses the built-in polymorphic comparison to compare for equality, and a built-in polymorphic hash function.
The built-in polymorphic comparison function fails for function types and for cyclic values.
There is also a functorial interface that lets you define your own equality and hash functions. So you can even have a hash table with keys that contain functions if you do a little extra work (assuming you don't expect to compare the functions for equality).
It is not difficult to make a hash table with tuples as keys:
# let my_table = Hashtbl.create 64;;
val my_table : ('_weak1, '_weak2) Hashtbl.t = <abstr>
# Hashtbl.add my_table (1, 2) "one two";;
- : unit = ()
# Hashtbl.add my_table (3, 4) "three four";;
- : unit = ()
# Hashtbl.find my_table (1, 2);;
- : string = "one two"

How do I define a generic (polymorphic) function in Rascal?

I would like to define a generic function to extract keys from a map, something like this:
public list[K] keys(map[K,V] aMap) {
return [ key | key:val <- aMap ];
}
Although no syntax error is given, this does not work. Is there a way to do it?
You can define this as
public list[&K] keys(map[&K,&V] aMap) {
return [ k | k <- aMap ];
}
Note that the keys are unordered, so it may make more sense to return them as a set instead of as a list. You can also always get the keys or values out as sets directly by projecting them out of the map, using either
aMap<0>
for the set of keys or
aMap<1>
for the set of values. Finally, the Set module contains a toList function, so you could do this in one line as
toList(aMap<0>)
which will give you the same result as calling the keys function.

F# pass multidimensional array of bool to function

How can I pass a multdimensional array of bools to a function in F#?
Thanks
Maybettle
There are two options depending on whether you're using actual 2D array (rectangular array) or jagged array (an array whose elements are arrays, with possibly different length):
If you're not sure which one to use, then it is good to know that jagged arrays are faster, but it may be easier to work with rectangular arrays (because you're sure about the dimensions).
let foo (ar:bool[,]) = ar.[0, 0] // Get element at specified coordinates
let bar (ar:bool[][]) = ar.[0].[0] // Get first array and then the element
To call the two functions, you can use the following syntax:
// Create array of arrays and call the function
bar [| [| true |] |]
// Creates array of arrays and converts it to multi-dimensional array
// You can also use plenty of functions from 'Array2D' module
foo (array2D [| [| true |] |])
If you want to write function that will be more general, you can also use sequence of sequences. This will be compatible with jagged arrays only, but you can also use the function with e.g. F# lists of lists or any .NET collection types.
let woo (ar:seq<#seq<bool>>) = Seq.head (Seq.head ar)
The #seq<..> type means that it can be sequence or any other derived type. This is needed for the element type, but not for the outer type, because F# automatically casts the outer type (but not elements).

F# iteration over a Dictionary

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

How do you declare the values of a dictionary entry as mutable?

The Google yields plenty of example of adding and deleting entries in an F# dictionary (or other collection). But I don't see examples to the equivalent of
myDict["Key"] = MyValue;
I've tried
myDict.["Key"] <- MyValue
I have also attempted to declare the Dictionary as
Dictionary<string, mutable string>
as well several variants on this. However, I haven't hit on the correct combination yet... if it is actually possible in F#.
Edit: The offending code is:
type Config(?fileName : string) =
let fileName = defaultArg fileName #"C:\path\myConfigs.ini"
static let settings =
dict[ "Setting1", "1";
"Setting2", "2";
"Debug", "0";
"State", "Disarray";]
let settingRegex = new Regex(#"\s*(?<key>([^;#=]*[^;#= ]))\s*=\s*(?<value>([^;#]*[^;# ]))")
do File.ReadAllLines(fileName)
|> Seq.map(fun line -> settingRegex.Match(line))
|> Seq.filter(fun mtch -> mtch.Success)
|> Seq.iter(fun mtch -> settings.[mtch.Groups.Item("key").Value] <- mtch.Groups.Item("value").Value)
The error I'm getting is:
System.NotSupportedException: This value may not be mutated
at Microsoft.FSharp.Core.ExtraTopLevelOperators.dict#37-2.set_Item(K key, V value)
at <StartupCode$FSI_0036>.$FSI_0036_Config.$ctor#25-6.Invoke(Match mtch)
at Microsoft.FSharp.Collections.SeqModule.iter[T](FastFunc`2 action, IEnumerable`1 sequence)
at FSI_0036.Utilities.Config..ctor(Option`1 fileName)
at <StartupCode$FSI_0041>.$FSI_0041.main#()
stopped due to error
f# has two common associative data structures:
The one you are most used to, the mutable Dictionary which it inherits that's to it's presence in the BCL and uses a hashtable under the hood.
let dict = new System.Collections.Generic.Dictionary<string,int>()
dict.["everything"] <- 42
The other is known as Map and is, in common functional style, immutable and implemented with binary trees.
Instead of operations that would change a Dictionary, maps provide operations which return a new map which is the result of whatever change was requested. In many cases, under the hood there is no need to make an entirely new copy of the entire map, so those parts that can be shared normally are. For example:
let withDouglasAdams = Map.add "everything" 42 Map.empty
The value withDouglasAdams will remain forever as an association of "everything" to 42. so if you later do:
let soLong = Map.remove "everything" withDouglasAdams
Then the effect of this 'removal' is only visible via the soLong value.
F#'s Map is, as mentioned, implemented as a binary tree. Lookup is therefore O(log n) whereas a (well behaved) dictionary should be O(1). In practice a hash based dictionary will tend to outperform the tree based one in almost all simple (low number of elements, low probability of collision) as such is commonly used. That said the immutable aspect of the Map may allow you to use it in situations where the dictionary would instead require more complex locking or to write more 'elegant' code with fewer side effects and thus it remains a useful alternative.
This is not however the source of your problem. The dict 'operator' returns an explicity immutable IDictionary<K,T> implementation (despite not indicating this in it's documentation).
From fslib-extra-pervasives.fs (note also the use of options on the keys):
let dict l =
// Use a dictionary (this requires hashing and equality on the key type)
// Wrap keys in an Some(_) option in case they are null
// (when System.Collections.Generic.Dictionary fails). Sad but true.
let t = new Dictionary<Option<_>,_>(HashIdentity.Structural)
for (k,v) in l do
t.[Some(k)] <- v
let d = (t :> IDictionary<_,_>)
let c = (t :> ICollection<_>)
let ieg = (t :> IEnumerable<_>)
let ie = (t :> System.Collections.IEnumerable)
// Give a read-only view of the dictionary
{ new IDictionary<'key, 'a> with
member s.Item
with get x = d.[Some(x)]
and set (x,v) = raise (NotSupportedException(
"This value may not be mutated"))
...
What error do you get? I tried the following and it compiles just fine
let map = new System.Collections.Generic.Dictionary<string,int>()
map.["foo"] <- 42
EDIT Verify that this code ran just fine as well .

Resources