IntMap changes type after innocent mapping - collections

consider this piece of code:Welcome to Scala version 2.8.0.r0-b20100714201327 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_20).
scala> val a = IntMap((1,1))
a: scala.collection.immutable.IntMap[Int] = IntMap((1,1))
scala> a.map(x => (x._1,x._2 + 1))
res23: scala.collection.immutable.Map[Int,Int] = Map((1,2))
header of IntMap.map says this
def map [B] (f: ((Int, T)) ⇒ B) : immutable.IntMap[B]
[use case] Builds a new collection by applying a function to all elements
of this immutable integer map.
How should I construct the lambda to return IntMap?

Under Scala 2.8, I get
scala> a.map(x => (x._1,x._2 + 1))
res0: scala.collection.immutable.IntMap[Int] = IntMap((1,2))

Related

Having a module and an instance of it as parameters to an OCaml function

I want to write a function that takes modules that implement a certain signature and instances of the same type as those modules, but apparently I can't do that because of an issue related to the scope of the module (the module and it's instance are both parameters, therefore the instance doesn't know the type of the module).
Here is an example:
let f (type a) (module M: Set.S with type elt = a) (pr: a -> unit) (m: M.t) =
M.iter pr m;;
Where M is a Set module with elements of type a, and pr can be a printer for elements of type a.
And the message of the error caused by it (which I don't find to be super clear):
Line 1, characters 69-78:
Error: This pattern matches values of type M.t
but a pattern was expected which matches values of type 'a
The type constructor M.t would escape its scope
I tried to solve this by considering that the problem is caused by the scope of the parameters covering only the body of the function, so I put the last argument inside the body of the function like this:
let f (type a) (module M: Set.S with type elt = a) (pr : a -> unit) =
fun (m : M.t) ->
M.iter pr m;;
But the error message is still present:
Line 2, characters 7-16:
Error: This pattern matches values of type M.t
but a pattern was expected which matches values of type 'a
The type constructor M.t would escape its scope
So is there a way to do it?
OCaml core language (outside of the module system) is not dependently typed. In fantasy syntax, your function would have type function (module M: Set.S with type elt = 'a) -> ('a -> unit) -> M.t. In this type, M is a value, thus the type is dependently typed, and cannot be implemented in OCaml.
In your case, it is possible to make the type not dependent by restricting the class of modules accepted as arguments with a with constraint
let f (type a t ) (module M: Set.S with type elt = a and type t = t)
pr m = M.iter pr m
module String_set = Set.Make(String)
let () = f (module String_set) ignore String_set.empty
A possible other solution is to store the value along with the first class module and its existential quantifications:
module type packed = sig
type a
module Impl: Set.S with type elt = a
val value: Impl.t
end
let g (type a) (module P: packed with type a = a)
pr = P.Impl.iter pr P.value
But for more complex functions, there is no other choices than using functors at the module level.
Aside: if you wonder why the module type Set.S with type elt = a and type t = t in the first variant above is a (necessary) restriction consider this packed module:
let random_int_set: (module Set.S with type elt = int) =
let compare =
if Random.int 3 > 1 then Stdlib.compare
else (fun x y -> Stdlib.compare y x)
in
let module S = Set.Make(struct type t = int let compare = compare end) in
(module S)
Here, the set type is based on a random compare function. Thus the type of set is incompatible with all other Sets. Consequently, it is only possible to use such module with a packed value:
module P = struct
type a = int
module Impl = (val random_int_set)
let value = Impl.empty
end
let () = g (module P) ignore

How to create and use my own structure/signature in SML/NJ?

I'm new to functional programming and I want to create my own structure/signature called Dictionary. So far I have this in file called dictionary-en.sml:
(* The signature DICTIONARY defines a type and a programming interface for
the dictionary data structure. The data structure allows us to store
data in the form of (key, value) pairs and to query the data using a key. *)
signature DICTIONARY =
sig
(* The structure has to implement a dictionary type. It defines key type,
which has to support equality checking, and a value type for the data
stored in the dictionary. *)
type (''key, 'value) dict
(* Creates an empty dictionary. *)
val empty: (''key, 'value) dict
(* Returns true if a key exists in the dictionary. *)
val exists: (''key, 'value) dict -> ''key -> bool
end
And I have this in file solution.sml:
structure Dictionary :> DICTIONARY =
struct
type (''key, 'value) dict = (''key * 'value) list
val empty = []
fun exists dict key =
case dict of
[] => false
| (k, _ )::rep => if k = key
then true
else exists rep key
end
But I don't how to use this.
When I wrote in REPL:
- Dictionary.exists [(3,"c"), (5, "e"), (7, "g")] 3;
I got this error:
stdIn:1.2-3.7 Error: operator and operand do not agree [tycon mismatch]
operator domain: (''Z,'Y) Dictionary.dict
operand: ([int ty] * string) list
in expression:
Dictionary.exists ((3,"c") :: (5,"e") :: (<exp>,<exp>) :: nil)
Can someone please help me? I don't know what I did wrong.
In the function
fun exists dict key =
case dict of
[] => []
| (k, _ )::rep => if k = key
then true
else exists rep key
I spot two issues:
You can't return [] in one place and true in another.
Instead of if P then true else Q, write P orelse Q.
You're using :> which means that the module is opaque, so you can only access the things specified in the signature. The internal list representation is not mentioned in the signature, so you can't refer to a dict as a list, even though you may know that that's how it's implemented. This is a feature.
I would probably call exists for member, since List.exists is a higher-order predicate, e.g. List.exists (fn x => x > 5) [3, 6, 9]. You could also deviate from any standard library naming and say containsKey and containsValue, or something like that.
Besides the insert function that molbdnilo suggested, you may like to have a fromList function.
Here's a refactored version (comments omitted for brevity, but I think your comments are good!):
signature DICTIONARY =
sig
type (''key, 'value) dict
val empty: (''key, 'value) dict
val member: ''key -> (''key, 'value) dict -> bool
val insert: (''key * 'value) -> (''key, 'value) dict -> (''key, 'value) dict
val fromList: (''key * 'value) list -> (''key, 'value) dict
end
structure Dictionary :> DICTIONARY =
struct
type (''key, 'value) dict = (''key * 'value) list
val empty = []
fun member key [] = false
| member key ((key2, _)::dict) =
key = key2 orelse member key dict
fun insert (key, value) [] = [(key, value)]
| insert (key, value) ((key2, value2)::dict) =
if key = key2
then (key, value) :: dict
else (key2, value2) :: insert (key, value) dict
fun fromList pairs = foldl (fn (pair, dict) => insert pair dict) empty pairs
end
But since you're building a dictionary module, there are two things you want to consider:
Make it possible to use some kind of binary tree as internal representation, requiring that the keys can be ordered rather than compared for equality.
Since Standard ML doesn't have special syntax like ''key to express that something can be ordered (Haskell generalises this as type classes, but Standard ML has only the special syntax ''key), this is a good case for using functors, which is the name given to higher-order modules, aka parameterised modules.
Here's an example signature, functor and structure that you can fill out:
signature ORD = sig
type t
val compare : t * t -> order
end
signature DICT = sig
type key
type 'value dict
val empty: 'value dict
val member: key -> 'value dict -> bool
val insert: key * 'value -> 'value dict -> 'value dict
val fromList: (key * 'value) list -> 'value dict
end
functor Dict (Ord : ORD) :> DICT = struct
type key = Ord.t
type 'value dict = (key * 'value) list
val empty = ...
fun member _ _ = raise Fail "not implemented"
fun insert _ _ = raise Fail "not implemented"
fun fromList _ = raise Fail "not implemented"
end
At this point you can change type 'value dict into using a binary tree, and when you need to decide whether to go left or right in this binary tree, you can write:
case Ord.compare (key1, key2) of
LESS => ...
| EQUAL => ...
| GREATER => ...
And when you need a dictionary where the key is some particular orderable type, you can create a module using this functor:
structure IntDict = Dict(struct
type t = int
val compare = Int.compare
end)
structure StringDict = Dict(struct
type t = string
val compare = String.compare
end)
See also Standard ML functor examples for more examples.
You can't access the internal representation; the entire interface is given by the signature.
You need to add to the signature some way to create a dictionary without depending on the representation used in a particular structure.
For instance,
val insert : (''key * 'value) -> (''key, 'value) dict -> (''key, 'value) dict
would let you write
Dictionary.exists (Dictionary.insert (3,"c") Dictionary.empty) 3;
Implementation left as an exercise.

Call Haskell DLL from Mathematica

Looking for a way to call a Haskell DLL from Mathematica, I've stumbled on this, for GNU R:
http://neilmitchell.blogspot.com.br/2011/10/calling-haskell-from-r.html
It is (to me) a beautiful example and I managed to make it work on Mathematica without modification through this spell:
Needs["NETLink`"]
hsStart = DefineDLLFunction["HsStart", "c:\\temp\\SumRoots.dll", "void", {}];
hsEnd = DefineDLLFunction["HsEnd", "c:\\temp\\SumRoots.dll", "void", {}];
sroot = DefineDLLFunction["sumRootsR", "c:\\temp\\SumRoots.dll", "double", {"int*", "double[]", "double*"}];
hsStart[];
resulta = 0;
lista = {9, 3.5, 5.58, 64.1, 12.54};
sroot[Length[lista], lista, resulta];
resulta
18.7805
hsEnd[];
Then I tried to modify the example to return a vector of doubles, instead of a single value:
Code in Haskell:
-- SumRoots.hs
{-# LANGUAGE ForeignFunctionInterface #-}
module SumRoots where
import Foreign
foreign export ccall acumSumR :: Ptr Int -> Ptr Double -> Ptr Double -> IO ()
acumSum :: [Double] -> [Double]
acumSum xs = scanl (\x y -> x+y) 0 xs
acumSumR :: Ptr Int -> Ptr Double -> Ptr Double -> IO ()
acumSumR n xs result = do
n <- peek n
xs <- peekArray n xs
pokeArray result $ acumSum xs
Code in C: (exactly the same of the mentioned blog post)
Compiling:
ghc -c SumRoots.hs
ghc -c StartEnd.c
ghc -shared -o SumRoots.dll SumRoots.o StartEnd.o
Code in Mathematica:
Needs["NETLink`"]
hsStart = DefineDLLFunction["HsStart", "c:\\temp\\SumRoots.dll", "void", {}];
hsEnd = DefineDLLFunction["HsEnd", "c:\\temp\\SumRoots.dll", "void", {}];
acums = DefineDLLFunction["acumSumR", "c:\\temp\\SumRoots.dll", "double[]", {"int*", "double[]", "double[]"}];
hsStart[];
lista = {9, 3.5, 5.58, 64.1, 12.54};
NETBlock#Module[{n, resultb}, n = Length[lista]+1;
resultb = NETNew["System.Double[]", n]; acums[n, lista, resultb];
NETObjectToExpression[resultb]]
{0., 0., 0., 0., 0., 0.}
The result should be {0.0, 9.0, 12.5, 18.08, 82.18, 94.72}. I'm not sure if this problem belongs to Mathematica or Haskell realm, but posting here is based on the fact that the GNU R call worked:
dyn.load("C:/temp/SumRoots.dll")
.C("HsStart")
acumSum <- function(input)
{
return(.C("acumSumR", n=as.integer(length(input)), xs=as.double(input), result=as.double(rep(0,length(input)+1)))$result)
}
input <- c(9,3.5,5.58,64.1,12.54)
acumSum(input)
So, can somebody give a hint on how to call this modified Haskell DLL function from Mathematica?
Environment:
SO: Windows 10 64-bit
Mathematica 8.0 64-bit
Haskell Platform 8.0.1 64-bit
GNU R 3.3.2 64-bit
Cheers,
Rand

Getting object instance by string name in scala

I need the object (or "singleton object" or "companion object"... anything but the class) defined by a string name. In other words, if I have:
package myPackage
object myObject
...then is there anything like this:
GetSingletonObjectByName("myPackage.myObject") match {
case instance: myPackage.myObject => "instance is what I wanted"
}
In scala 2.10 we can do like this
import scala.reflect.runtime.universe
val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
val module = runtimeMirror.staticModule("package.ObjectName")
val obj = runtimeMirror.reflectModule(module)
println(obj.instance)
Scala is still missing a reflection API. You can get the an instance of the companion object by loading the companion object class:
import scala.reflect._
def companion[T](implicit man: Manifest[T]) : T =
man.erasure.getField("MODULE$").get(man.erasure).asInstanceOf[T]
scala> companion[List$].make(3, "s")
res0: List[Any] = List(s, s, s)
To get the untyped companion object you can use the class directly:
import scala.reflect.Manifest
def companionObj[T](implicit man: Manifest[T]) = {
val c = Class.forName(man.erasure.getName + "$")
c.getField("MODULE$").get(c)
}
scala> companionObj[List[Int]].asInstanceOf[List$].make(3, "s")
res0: List[Any] = List(s, s, s)
This depends on the way scala is mapped to java classes.
Adjustment to Thomas Jung's answer above: you would do better to say companion[List.type] because a) this should be a stable way to refer to it, not dependant on the name mangling scheme and b) you get the unerased types.
def singleton[T](implicit man: reflect.Manifest[T]) = {
val name = man.erasure.getName()
assert(name endsWith "$", "Not an object: " + name)
val clazz = java.lang.Class.forName(name)
clazz.getField("MODULE$").get(clazz).asInstanceOf[T]
}
scala> singleton[List.type].make(3, "a")
res0: List[java.lang.String] = List(a, a, a)
Barring reflection tricks, you can't. Note, for instance, how the method companion is defined on Scala 2.8 collections -- it is there so an instance of a class can get the companion object, which is otherwise not possible.
Scala 2:
val runtimeMirror = universe.runtimeMirror(this.getClass.getClassLoader)
val objectClass = Class.forName("org.test.MyObject$")
val moduleSymbol = runtimeMirror.staticModule(objectClass.getName)
val moduleMirror = runtimeMirror.reflectModule(moduleSymbol)
val instance = moduleMirror.instance
Or just use Java API to get the value from the static field:
val instance = objectClass.getField("MODULE$").get(null)
Mind the $ in the object name.

Functors in OCaml

I am having a bit of a problem with a functor (and it's resultant type). Below, I have a Set functor that uses an Ordered type. I actually used the set.ml that comes with OCaml for some guidance, but I seem to be doing everything ahem right. I created an Ordered module with integers and applied it to the Set functor to get the last module on this code sample, IntSet.
The next line fails, when I try to insert an integer. I get the following type error:
Error: This expression has type int but is here used with type
SetInt.elt = Set(OrdInt).elt
Don't get me wrong, the type system is correct here. The top level reports that the type of the SetInt.elt is Set(OrdInt).elt, but when I do the same operations to set up a Set using the one provided by OCaml the 'same' line is, SetInt.elt = OrderedInt.t. Seems like I should be getting SetInt.elt = Ordered.t.
This is so simple, I'm probably just missing some stupid detail! argh!
Please Note: I have simplified the member/insert functions here since this issue has to do with types.
module type Ordered =
sig
type t
val lt : t -> t -> bool
val eq : t -> t -> bool
val leq : t -> t -> bool
end
module type S =
sig
type elt
type t
exception Already_Exists
val empty : t
val insert : elt -> t -> t
val member : elt -> t -> bool
end
module Set (Elt:Ordered) : S =
struct
type elt = Elt.t
type t = Leaf | Node of t * elt * t
exception Already_Exists
let empty = Leaf
let insert e t = t
let member e t = false
end
module OrdInt : Ordered =
struct
type t = int
let lt a b = a < b
let eq a b = a = b
let leq a b = a <= b
end
module IntSet = Set (OrdInt)
(* line that fails *)
let one_elm = IntSet.insert 1 IntSet.empty
You need to change these two lines
module Set (Elt:Ordered) : S =
module OrdInt : Ordered =
to
module Set (Elt:Ordered) : S with type elt = Elt.t =
module OrdInt : Ordered with type t = int =
Without these, the modules will not have signatures that expose the types elt and t as int.
[Edit]:
The set.ml doesn't have the 'with' bit, because there's a sml.mli, which declares the signature for the functor and it does have the 'with'. Also, OrdInt doesn't need 'with' if you don't explicitly specify a signature for it, like this:
module OrdInt =
You can also construct the set by defining the module in place:
module IntSet = Set (struct
type t = int
let lt a b = a < b
let eq a b = a = b
let leq a b = a <= b
end)

Resources