How is the scoping of variables handled during exceptions? I suppose this will be language specific, and answers for any specific language are greatly appreciated. At least maybe the big ones? C++, python, Java. This is what I mean:
python
try:
for k, v in map.iteritems():
cnf.conf.set( section, k, v )
for i, j in map2.iteritems():
dosomethingelse()
for m in range(10):
morestuff()
except SpecificError:
vars = (k, v, i, j, m)
finally:
vars in scope #?
Or something more complicated, like nested blocks:
try:
try:
for k, v in map.iteritems():
cnf.conf.set( section, k, v )
for i, j in map2.iteritems():
dosomethingelse()
for m in range(10):
morestuff()
except SpecificError:
vars = (k, v, i, j, m)
except:
vars in scope #?
In java, I believe you can not do the following:
try {
String s = "Hello, finally!";
...
}
finally {
System.out.println(s);
}
You must instead do:
String s = null;
try {
s = "Hello, finally!";
...
}
finally {
System.out.println(s);
}
In other words, the scope of the variable is limited to the block in which it is defined.
HTH
Related
I'm an economics student slowly switching from MATLAB to Julia.
Currently, my problem is that I don't know how to declare (preallocate) a vector that could store interpolations.
Specifically, when I execute something close to:
function MyFunction(i)
# x, y vectors are some functions of 'i' defined here
f = LinearInterpolation(x,y,extrapolation_bc=Line())
return f
end
g = Vector{Function}(undef, N)
for i = 1:N
g[i] = MyFunction(i)
end
I get:
ERROR: LoadError: MethodError: Cannot `convert` an object of type Interpolations.Extrapolation{Float64,1,Interpolations.GriddedInterpolation{Float64,1,Float64,Gridded{Linear},Tuple{Array{Float64,1}}},Gridded{Linear},Line{Nothing}} to an object of type Function
If I, instead of g=Vector{Function}(undef, N), declare g=zeros(N), I get a similar error message (ending with with ...Float64 rather than with ... Function).
When I, instead, declare:
g = Interpolations.Extrapolation{Float64,1,Interpolations.GriddedInterpolation{Float64,1,Float64,Gridded{Linear},Tuple{Array{Float64,1}}},Gridded{Linear},Line{Nothing}}(N)
I get:
LoadError: MethodError: no method matching Interpolations.Extrapolation{Float64,1,Interpolations.GriddedInterpolation{Float64,1,Float64,Gridded{Linear},Tuple{Array{Float64,1}}},Gridded{Linear},Line{Nothing}}(::Int64) Closest candidates are: Interpolations.Extrapolation{Float64,1,Interpolations.GriddedInterpolation{Float64,1,Float64,Gridded{Linear},Tuple{Array{Float64,1}}},Gridded{Linear},Line{Nothing}}(::Any, !Matched::Any) where {T, N, ITPT, IT, ET}
When I don't declare "g" at all, then I get:
ERROR: LoadError: UndefVarError: g not defined
Finally, when I declare:
g = Vector{Any}(undef, N)
the code works, though I'm afraid this might induce some type-change of a variable g, thereby slowing down my performance-sensitive code.
How, ideally then, should I declare g in this case?
EDIT:
In reality, my problem is a bit more complex, more like the following:
function MyFunction(i)
# x, y vectors are some functions of 'i' defined here
f = LinearInterpolation(x,y,extrapolation_bc=Line())
h = is a T-vector of some functions of x,y
A = is some matrix depending on x,y
return h, A, f
end
h = Matrix{Function}(undef, T, N)
A = zeros(T,I,N)
g = Vector{Any}(undef, N)
for i = 1:N
h[:,i], A[:,:,i], g[i] = MyFunction(i)
end
So, when I use either comprehension or broadcasting (like h, A, g = [MyFunction(i) for i in 1:N] or h, A, g = MyFunction.(1:N)), as users Benoit and DNS suggested below, the outputs of my function are 3 tuples, h, A, g, each containing {h[i], A[i], g[i]} for i=1,2,3. If I use only 1 output variable on the LHS, instead, i.e.: MyOutput = [MyFunction(i) for i in 1:N] or MyOutput[i] = MyFunction.(1:N), then MyOutput becomes a vector with N tuple entries, every tuple consisting of {h[i], A[i], g[i]} i=1,2,3,...,N. I bet there's a way of extracting these elements from the tuples in MyOutput and filling them inside h[:,i], A[:,:,i], g[i], but that seems a bit cumbersome and slow.
You could do
f = MyFunction(1)
g = Vector{typeof(f)}(undef, N)
g[1] = f
for i = 2:N
g[i] = MyFunction(i)
end
I think also map should figure out the type:
map(MyFunction, 1:N)
A simple solution is to use a comprehension:
g = [MyFunction(i) for i in 1:N]
or elegantly use the dot syntax:
g = MyFunction.(1:N)
(Credit to DNF for the dot-syntax solution suggested in the comments.)
I have a function that looks like
function eom!(du, u, p)
#views a, b = u[:,1], u[:,2];
#views da, db = du[:,1], du[:,2];
y = # some stuff involving p and a;
da .= f(a, b, y);
db .= g(b, a);
end
I now want to create a second a function that is the exact same, except the last line reads
db .= g(b, y);
How can I do this most cleanly? Of course, I could just copy and paste and give the functions slightly different names, but this seems unideal, especially if, as is plausible, I later want more functions where the second argument of g could be something else. Is there perhaps a way that I could pass into the function eom! an expression (via the argument p) that would specify the second argument of g? Or is there a way I could make some function eom_generator which can output all of the functions that I want? Perhaps macros are the central tool in doing this, but I am not sure.
You could produce a closure:
function eom_generator(g)
return function eom!(du, u, p)
#views a, b = u[:,1], u[:,2]
#views da, db = du[:,1], du[:,2]
y = nothing # some stuff involving p and a;
da .= f(a, b, y)
db .= g(a, b, y)
end
end
const eom1! = eom_generator((a, b, y) -> g(b, a))
const eom2! = eom_generator((a, b, y) -> g(b, y))
But since this is at the core of a differential equation, be sure to test whether you don't have any performance issues that way.
If you decide that you really need metaprogramming, you can use #eval in a loop:
for (i, expr) in enumerate((:(g(b, a)), :(g(b, y))))
#eval function $(Symbol("eom", i, "!"))(du, u, p)
#views a, b = u[:,1], u[:,2]
#views da, db = du[:,1], du[:,2]
y = nothing # some stuff involving p and a;
da .= f(a, b, y)
db .= $expr
end
end
end
I'm just learning a haskell and seems like all is good even scary monads are not a big deal for me. But I can't get to real practiacal stuff at all.
My first practical task for haskell I choosed as follows:
Given a JSON describing some binary file's format to parse that file.
JSON has some deeply nested structure with lists of assocoative lists (dictionaries) of lists etc with endpoints as numbers or strings.
So first of all I want to be able to map other those endpoints (to have functor class for jsons data) converting some strings to numbers in particular. Also it would be nice to be able to fold all those endpoints as well.
I came up with some python code easily. But can't go any far with haskell.
So what your suggestions for implementing things in haskell? It really would be nice to hear some advise for solutions using libraries to greatest extent and not handwrite all the stuff from scratch.
Thanks in advance!
added---
example of what I have in python
Some helper functions:
islist = lambda l: isinstance(l, collections.Iterable) and not isinstance(l, (str, bytes))
isdict = lambda d: isinstance(d, collections.Mapping)
isiter = lambda i: islist(i) or isdict(i)
def iterable(d):
if isdict(d):
i = d.items()
elif islist(d):
i = enumerate(d)
else:
raise ValueError
return i
Iterator over nested json data:
def nested_iter(nested, f = lambda *args: None):
for key, value in iterable(nested):
if not isiter(value):
f(nested, key)
yield key, value
else:
yield from nested_iter(value, f)
now I can substitute some numbers with lists of keys:
def list_from_num(d, k):
if type(d[k]) == int:
d[k] = [k]*d[k]
list(nested_iter(typedef, list_from_num))
or I can substitute some strings with some other nested data with the same key name
def nest_dicts(defs, d, k):
if d[k] in defs.keys():
d[k] = deepcopy(defs[d[k]])
if isiter(d[k]):
list(nested_iter(d[k], partial(nest_dicts, defs)))
list(nested_iter(typedef, partial(nest_dicts, typedef)))
or can just flatten data
list(nested_iter(d))
parsing binary is a bit more evolved but it is nothing more as passing to iterator one more function
Well this is my solution.
It uses Control.Lens, Data.Aeson.Lens, Control.Lens.Plated
One can use transform from Uniplate or Lens.Plated to transform values.
for example to substitute each number with list of key values of length of that number:
n2k :: T.Text -> Value -> Value --import qualified Data.Text as T
n2k s (Number x)
| isInteger x = case toBoundedInteger x of
Just n -> Array (V.replicate n (String s)) -- import qualified Data.Vector as V
_ -> Number x
| otherwise = Number x
n2k _ v = v
f (Object o) = Object $ imap n2k o --imap from Data.Map.Lens
f x = x
j2 = transform f j --transform JSON j using function f
to substitute string with data with same key:
-- o is hashmap where we are looking for keys to substitute strings
h (String s) = fromMaybe (String s) (H.lookup s o) --import qualified Data.HashMap.Lazy as H
h x = x
j2 = transform h j
just get all numbers into list:
l = [x | Number x <- universe j]
I want to implement the Fisher-Yates algorithm (an in-place array shuffle) without side effects by using an STArray for the local mutation effects, and a functional random number generator
type RNG[A] = State[Seed,A]
to produce the random integers needed by the algorithm.
I have a method def intInRange(max: Int): RNG[Int] which I can use to produce a random Int in [0,max).
From Wikipedia:
To shuffle an array a of n elements (indices 0..n-1):
for i from n − 1 downto 1 do
j ← random integer such that 0 ≤ j ≤ i
exchange a[j] and a[i]
I suppose I need to stack State with ST somehow, but this is confusing to me. Do I need a [S]StateT[ST[S,?],Seed,A]? Do I have to rewrite RNG to use StateT as well?
(Edit) I don't want to involve IO, and I don't want to substitute Vector for STArray because the shuffle wouldn't be performed in-place.
I know there is a Haskell implementation here, but I'm not currently capable of understanding and porting this to Scalaz. But maybe you can? :)
Thanks in advance.
You have lots of options. One simple (but not very principled) one would be just to lift both the Rng and ST operations into IO and then work with them together there. Another would be to use both an STRef[Long] and an STArray in the same ST. Another would be to use a State[(Long, Vector[A]), ?].
You could also use a StateT[State[Long, ?], Vector[A], ?] but that would be kind of pointless. You could probably use a StateT (for the RNG state) over an ST (for the array), but again, I don't really see the point.
It's possible to do this pretty cleanly without side effects with just Rng, though. For example, using NICTA's RNG library:
import com.nicta.rng._, scalaz._, Scalaz._
def shuffle[A](xs: Vector[A]): Rng[Vector[A]] =
(xs.size - 1 to 1 by -1).toVector.traverseU(
i => Rng.chooseint(0, i).map((i, _))
).map {
_.foldLeft(xs) {
case ((i, j), v) =>
val tmp = v(i)
v.updated(i, v(j)).updated(j, tmp)
}
}
Here you just pick all your swap operations in the Rng monad, and then fold over them with your collection as the accumulator, swapping as you go.
Here is a more or less direct translation from the Haskell version you linked that uses a mutable STArray. The Scalaz STArray doesn't have an exact equivalent of the listArray function, so I've made one up. Otherwise, it's a straightforward transliteration:
import scalaz._
import scalaz.effect.{ST, STArray}
import ST._
import State._
import syntax.traverse._
import std.list._
def shuffle[A:Manifest](xs: List[A]): RNG[List[A]] = {
def newArray[S](n: Int, as: List[A]): ST[S, STArray[S, A]] =
if (n <= 0) newArr(0, null.asInstanceOf[A])
else for {
r <- newArr[S,A](n, as.head)
_ <- r.fill((_, a: A) => a, as.zipWithIndex.map(_.swap))
} yield r
for {
seed <- get[Seed]
n = xs.length
r <- runST(new Forall[({type λ[σ] = ST[σ, RNG[List[A]]]})#λ] {
def apply[S] = for {
g <- newVar[S](seed)
randomRST = (lo: Int, hi: Int) => for {
p <- g.read.map(intInRange(hi - lo).apply)
(a, sp) = p
_ <- g.write(sp)
} yield a + lo
ar <- newArray[S](n, xs)
xsp <- Range(0, n).toList.traverseU { i => for {
j <- randomRST(i, n)
vi <- ar read i
vj <- ar read j
_ <- ar.write(j, vi)
} yield vj }
genp <- g.read
} yield put(genp).map(_ => xsp)
})
} yield r
}
Although the asymptotics of using a mutable array might be good, do note that the constant factors of the ST monad in Scala are quite large. You may be better off just doing this in a monolithic block using regular mutable arrays. The overall shuffle function remains pure because all of your mutable state is local.
This is amost the same as Travis solution only difference is that it uses the State monad. I wanted to find a minimal set of imports but I finally gave up:
import com.nicta.rng.Rng
import scalaz._
import Scalaz._
object FisherYatesShuffle {
def randomJ(i: Int): Rng[Int] = Rng.chooseint(0,i)
type Exchange = (Int,Int)
def applyExchange[A](exchange: Exchange)(l: Vector[A]): Vector[A] = {
val (i,j) = exchange
val vi = l(i)
l.updated(i,l(j)).updated(j,vi)
}
def stApplyExchange[A](exchange: Exchange): State[Vector[A], Unit] = State.modify(applyExchange(exchange))
def shuffle[A](l: Vector[A]): Rng[Vector[A]] = {
val rngExchanges: Rng[Vector[Exchange]] = (l.length - 1 to 1 by -1).toVector.traverseU { i =>
for {
j <- randomJ(i)
} yield (i, j)
}
for {
exchanges <- rngExchanges
} yield exchanges.traverseU(stApplyExchange[A]).exec(l)
}
}
Given a higher-order function like the following:
let call (f : unit -> 'a) = f()
And another function:
let incr i = i + 1
Is there a way to pass incr to call, without using a lambda: (fun () -> incr 1)?
Obviously, passing (incr 1) does not work, as the function is then "fully applied."
EDIT
To clarify: I'm wondering if there's a way to curry a function, such that it becomes a function: unit -> 'a.
You can define such a shortcut yourself:
let ap f x = fun () -> f x
call (ap incr 1)
If the function you want to transform happens to be a pure function, you can define the constant function instead:
let ct x _ = x (* const is reserved for future use :( *)
call (ct (incr 1))
It looks more like an attempt to add laziness to strict F# then some kind of currying.
And in fact there is a built in facility for that in F#: http://msdn.microsoft.com/en-us/library/dd233247.aspx - lazy keyword plus awkward Force:
Not sure if it's any better than explicit lambda, but still:
let incr i =
printf "incr is called with %i\n" i
i+1
let call (f : unit -> 'a) =
printf "call is called\n"
f()
let r = call <| (lazy incr 5).Force
printf "%A\n" r