I am using the z3py API (4.3.0). I can easily translate an expression expr from the default context to a new context target_ctx, using expr.translate(target_ctx). But how can I translate from a given context ctx into the default Z3 context? Is there a way to obtain the default Context from the Python API?
It can be accessed through main_ctx().
Here's the Python API describing main_ctx: http://research.microsoft.com/en-us/um/redmond/projects/z3/z3.html#-main_ctx
Another way to do this is with object.ctx from any object created without a reference to a specific context (which uses the global context main_ctx() by default).
Here's the Python API describing Context which discusses some of this: http://research.microsoft.com/en-us/um/redmond/projects/z3/z3.html#Context
Here's an example showing these approaches (z3py link: http://rise4fun.com/Z3Py/1sN ):
x, y = Reals('x y')
print x.ctx == y.ctx # True
ctx_default = x.ctx
print x.ctx == main_ctx() # True
ctx1 = Context()
x1, y1 = Reals('x1 y1', ctx1)
print ctx_default == x1.ctx # False
Related
I want to create a flow that creates a new source (it will be a persistence query) out of incoming elements, and then flattens the results. Something like this simplified example:
var z = Source.Single(1).ConcatMany(i => Source.Single(i));
this code compiles and works as expected. My problem is that when I translate it to F#:
let z = Source.Single(1).ConcatMany(fun i -> Source.Single(i))
I get an error saying
This expression was expected to have type
'IGraph<SourceShape<'a>,Akka.NotUsed>'
but here has type
'Source<int,Akka.NotUsed>'
I think that the cause of that is that F# handles co/contravariance differently than C# and cannot simply convert these generic specializations (https://github.com/fsharp/fslang-suggestions/issues/162), but I cannot figure out a way to make a convertion between an int and a SourceShape<int>. Is it possible to convert this example to F#?
Looking at the code on GitHub, it appears that Source<TOut, TMat> is a direct implementation of IGraph, so you should just be able to cast it:
public sealed class Source<TOut, TMat> : IFlow<TOut, TMat>, IGraph<SourceShape<TOut>, TMat>
let z = Source.Single(1).ConcatMany(fun i -> Source.Single(i) :> IGraph<SourceShape<int>,Akka.NotUsed>)
I think the biggest difference between the C# and F# usage is that C# will automatically do the upcast for you.
One workaround that I found is to use Akkling.Streams wrapper library:
open Akkling.Streams
let x =
Source.singleton 1
|> Source.collectMap(fun x -> Source.singleton x)
the question how to do this without Akkling remains open.
Using the Fsharp.Compiler.Serice Interactive API I'd like to set variables to my FsiEvaluationSession object. Is this possible? Or is there another way to embed f# into an application for embedded-scripting purposes?
I don't think there is a direct way to do this, but there is a lovely workaround:
// Define a mutable variable with default value
fsiSession.EvalInteraction "let mutable myVar = Unchecked.defaultof<int>"
// Create a function that sets the value of the variable
let f = evalExpressionTyped<int -> unit> "fun x -> myVar <- x"
// Run the function to set the value of `myVar` to whatever we want
f 42
// As a bonus, use variable shadowing to make it immutable
fsiSession.EvalInteraction "let myVar = myVar"
This uses the evalExpressionTyped helper from the FCS documentation.
I would like to write the following:
module A =
type Token
let foo Token =
module B =
type Token
let foo Token =
let run (m : module) =
m.B
|> m.foo
basically a function that's generic in the module. Is there a way to do this in F#?
As kvb pointed out in a comment, it is hard to give an answer without a realistic example, because the best approach will depend on what you're actually trying to do.
In this trivial example, I would probably use F# interface to represent Token and add Foo as a member. Assuming that Foo returns an int, you can write the definition like this:
type Token =
abstract Foo : unit -> int
Then you can implement different tokens either using classes (which is quite heavyweight) or using object expressions. For example:
let tok = { new Token with
member x.Foo () = 42 }
The code that corresponds to your run function is just a call of the Foo member: tok.Foo()
I want to create a couple of computational expressions that would be used to access the database and return a list of items like so (I also have questions in the code comments):
let foo x y z = proc "foo" {
let! cmd = proc.CreateCommand() // can I do this?
do! In "x" DbType.Int32 // would i gain anything by replacing DbType with a union
// type since the names would match actual data types?
do! In "y" DbType.String 15;
cmd?x <- x
cmd?y <- y
use! r = cmd.ExecuteReader() // would this be bad form for creating a workflow builder?
return! r {
let item = MyItem()
do! item.a <- r.GetInt32("a")
do! item.a <- r.GetString("b")
do! item.c <- r.GetDateTime("c")
yield! item
}
}
How can I create a workflow builder such that an instance of it takes a parameter?
let proc name = ProcedureBuilder(connStr, factory) // how do I do this?
Yes, you can do this. You can use computation expression syntax after any expression with a type statically known to expose the right methods. So the following code works (but doesn't do anything particularly interesting):
let f x = async
let v = f "test" { return 1 }
Here, f has type 'a -> AsyncBuilder, so f "test" has type AsyncBuilder and can be followed with computation expression syntax. Your example of let proc name = ProcedureBuilder(connStr, factory) is perfectly fine, assuming that ProcedureBuilder is defined appropriately, though you presumably want name to appear somewhere in the constructor arguments.
The answer from Keith (kvb) is correct - you can use parameterized computation builders. The syntax of computation expressions is:
<expr> { <cexpr> }
So, the builder can be created by any expression. Usually, it is some value (e.g. async) but it can be a function call or even a constructor call. When using this, you would typically define a parameterized builder and then pass the argument to a constructor using a function (as #kvb suggests).
I actually wrote an example of this, not a long time ago, so I can share an example where - I think - this is quite useful. You can find it on F# snippets: http://fssnip.net/4z
The example creates a "special" asynchronous computation builder for ASP.NET MVC that behaves just like standard async. The only difference is that it adds Run member that uses AsyncManager (provided by ASP.NET) to execute the workflow.
Here are some relevant parts from the snippet:
/// A computation builder that is almost the same as stnadard F# 'async'.
/// The differnece is that it takes an ASP.NET MVC 'AsyncManager' as an
/// argumnet and implements 'Run' opration, so that the workflow is
/// automatically executed after it is created (using the AsyncManager)
type AsyncActionBuilder(asyncMgr:Async.AsyncManager) =
// (Omitted: Lots of boilerplate code)
/// Run the workflow automatically using ASP.NET AsyncManager
member x.Run(workflow) =
// Use 'asyncMgr' to execute the 'workflow'
The snippet wraps the construction in a base class, but you could define a function:
let asyncAction mgr = new AsyncActionBuilder(mgr)
And then use it to define asynchronous action in ASP.NET MVC:
member x.LengthAsync(url:string) = asyncAction x.AsyncManager {
let wc = new WebClient()
let! html = wc.AsyncDownloadString(url)
return html.Length }
I need to use OGNL for reading some properties from Java object. OGNL is completely new thing to me. The documentation available for OGNL is OGNL's website is really confusing to me.
So anyone can provide a simple HelloWorld example for using OGNL (or any link to a tutorial is also helpful).
Try this:
Dimension d = new Dimension(2,2);
String expressionString = "width";
Object expr = Ognl.parseExpression(expressionString);
OgnlContext ctx = new OgnlContext();
Object value = Ognl.getValue(expr, ctx, d);
System.out.println("Value: " + value);
If the intention is only to read properties from an object then PropertyUtils.getProperty (from commons-beanutils) may suffice. However, if the intention is to evaluate conditionals and such, then Ognl may benefit.
Here is the same Dimension example with a boolean:
Dimension d = new Dimension();
d.setSize(100,200) ;// width and height
Map<String,Object> map = new HashMap<String,Object>();
map.put("dimension", d);
String expression = "dimension.width == 100 && dimension.height == 200";
Object exp = Ognl.parseExpression(expression);
Boolean b = (Boolean) Ognl.getValue(exp,map);
// b would evaluate to true in this case
OGNL allows you to access objects fields and methods via string expressions which becomes very useful when you have lose coupled architecture between data and it's consumers. It's using reflection under the hood but definitely speeds up development compared to a pure reflection approach.
Some one line examples
System.out.println(Ognl.getValue("x", new Point(5,5)));
System.out.println(Ognl.getValue("size", new ArrayList<Object>()));
Documentation already has a number of basic and more advanced ognl expressions.
Here is an example helloworld for jython (python that compiles to java).
from ognl import Ognl, OgnlContext
from java.lang import String
exp = Ognl.parseExpression("substring(2, 5)")
print Ognl.getValue(exp, OgnlContext(), String("abcdefghj"))