Tree of unary operators - parsing

I want to parse expressions like
a
++a
a++
++a++
++a++++
The pre-increment operator has precedence over the post-increment operator.
The parsers I have are these:
public static readonly TokenListParser<LangToken, UnaryOperator> Increment = Token.EqualTo(LangToken.DoublePlus).Select(x => UnaryOperators.Increment);
public static readonly TokenListParser<LangToken, UnaryOperator> Decrement = Token.EqualTo(LangToken.DoubleMinus).Select(x => UnaryOperators.Decrement);
public static readonly TokenListParser<LangToken, Expression> Identifier = Token.EqualTo(LangToken.Identifier).Select(x => (Expression)new Id(x.ToStringValue()));
public static readonly TokenListParser<LangToken, Expression> A =
from c in Parse.Ref(() => Expression)
from op in Increment.Or(Decrement)
select (Expression)new OpNode(op, c);
public static readonly TokenListParser<LangToken, Expression> B =
from op in Increment.Or(Decrement)
from c in Parse.Ref(() => Expression)
select (Expression)new OpNode(op, c);
public static readonly TokenListParser<LangToken, Expression> Expression = A.Or(B).Or(Identifier);
However, when I parse a simple expression like "a++" using the Expression parser, the test hangs. I suppose that it's due to a recursion problem.
But what's the problem and how to solve it?

Related

Need help converting C# to F#

I'd like to know how to convert this code line by line from C# to F#. I am not looking to use any kind of F#'s idioms or something of the like. I am trying to understand how to enumaration and reflcetion in F#.
using System.Linq;
namespace System.Collections.Generic
{
public static class EnumerableExtensions
{
private static readonly Random random;
static EnumerableExtensions()
{
random = new Random();
}
public static T Random<T>(this IEnumerable<T> input)
{
return input.ElementAt(random.Next(input.Count()));
}
}
}
You can define extensions as static methods in a type, but you have to mark those with the Extension attribute. A direct rewrite of your C# code would be:
open System.Runtime.CompilerServices
[<Extension>]
type EnumerableExtensions() =
static let rnd = System.Random()
[<Extension>]
static member Random(input:seq<_>) =
input |> Seq.item (rnd.Next(Seq.length input))
[1;2;3].Random()

How to set a default value for an optional positional parameter of type Function?

I am passing a Function as an optional parameter to the constructor but I can't assign a default value.
void main() {
Person p = Person();
print(p.foo('Hello'));
}
class Person {
final String Function(String) foo;
Person({this.foo});
}
now trying to assign a default value: Person({this.foo = (val) {return val;});
produces the error: Error: Not a constant expression. I am aware the parameter must be const but using const or even static infront of (val) {return val;} does not work.
Does anyone have an idea how to solve this problem?
You can try this:
void main() {
Person pLower = Person(foo: (a) => a.toLowerCase());
print(pLower.foo('Hello'));
Person pDefault = Person();
print(pDefault.foo('Hello'));
}
class Person {
static String defaultFoo(String a) => a.toUpperCase();
final String Function(String) foo;
Person({this.foo = defaultFoo});
}
Output
hello
HELLO
You can only use constant values (aka. compile-time constants) as default values.
You cannot create a constant function literal, so there is no way to write the function in-line in the constructor.
However, references to top-level or static functions are constants, so you can declare the default value function as a static function or top-level function.
void main() {
Person p = Person();
print(p.foo('Hello')); // Prints "Hello"
}
class Person {
final String Function(String) foo;
Person({this.foo = _identity});
static String _identity(String value) => value;
}
// or as top-level.
// String _identity(String value) => value;
You can (and should) choose to make the function public if the default value is on an instance method, and you expect anyone to extend or implement your class. In that case, they need to declare the same default value.
Another option, which is often at least as useful, is to not use a default value, but replace a null before using the value:
class Person {
final String Function(String) foo;
Person({String Function(String) foo}) : foo = foo ?? _identity;
static String _identity(String value) => value;
}
or even using a non-constant value:
class Person {
final String Function(String) foo;
Person({String Function(String) foo}) : foo = (foo ?? (String x) => x);
}
For a constructor, it makes very little difference. If it was an instance method instead, using ?? to replace null avoids subclasses having to use the exact same function as default value.
Personally I recommend always using ?? instead of a default value. It's more flexible since it allows non-constant values. For non-function default values, you'll have to document the default behavior instead of just letting the dartDoc show {int x = 42}, but for functions, you'll have to document them anyway.

Microsoft Solver Foundation and F#

I'm trying to convert this MS Solver Foundation example from C# to F#, but constantly running into problems with type conversions, in particular in section 5, where C# accepts implicit conversion from double to Rational, something F# does not accept - any ideas how to resolve? The Rational type in itself is a puzzle for me as seems virtually impossible to initialize apart from setting it to the predefined Rational.One or Rational.Zero. Any ideas? See a minimalist down-scaled version below (without using any arrays or anything).
let main argv =
printfn "%A" argv
Console.WriteLine("\nBegin Solver demo\n")
let mean = 1.0
let solver = new InteriorPointSolver()
let allocation = ref 0
solver.AddVariable("MSFT", allocation) |> ignore
solver.SetBounds(!allocation, Rational.Zero, Rational.One)
let expRet = ref 0
solver.AddRow("expRet", expRet) |> ignore
solver.SetBounds(!expRet, Rational.Zero, Rational.PositiveInfinity)
let unity = ref 0
solver.AddRow("Investments sum to one", unity) |> ignore
solver.SetBounds(!unity, Rational.One, Rational.One)
solver.SetCoefficient(!expRet, !allocation, Rational.)
solver.SetCoefficient(!unity, !allocation, Rational.One);
Console.WriteLine("\nEnd Solver demo\n")
Console.ReadLine() |> ignore
0 // return an integer exit code
This is an old post, but no one has answered, and this information may be useful to others.
I don't know F# (so anyone who does, please edit my syntax), but the following methods in the Rational class should be of use. You will also need the BigInteger class from the Microsoft.SolverFoundation.Common name space.
(see https://learn.microsoft.com/en-us/previous-versions/visualstudio/ff526610)
First, as you point out, you can construct a Rational directly from other types using any of the many "implicit" constructors:
let Rational rat5 = Rational.op_Implicit(5.0:float)
let Rational rat2 = Rational.op_Implicit(2:int)
where I am guessing F# syntax.
As another quite illustrative example, monetary values (e.g. $10.43) can rarely be represented exactly with doubles. (The only "cents" values that wind up exact in a double are xx.00, xx.25, xx.50 and xx.75, all others wind up with numerical errors/differences.) So we often have to be careful when constructing a rational from a double that purports to represent a monetary value. This provides a good sample of another method of constructing rationals:
let BigInteger bi100 = BigInteger.op_Implicit(100:int)
let float mv = 1000000000000.43 //I am assuming this gets classified by F# as a double.
//Now, we assume mv is any double that represents a monetary value, and so should be an even 2 decimal places in base 10
//I have no idea how to Round in F#, nor how to cast to an integer - I have guessed - but should illustrate the idea if it is not valid F#
let BigInteger cents = BigInteger.op_Implicit( ( Round(mv * 100.0) ):int ) //get exact monetary value, in cents
let Rational ratMv = Rational.Get(cents:BigInteger, bi100:BigInteger)
and so we have constructed a Rational, from two BigInteger types, that exactly represents a monetary value mv stored as a double.
Here is the entire Rational interface, albeit in c#-syntax:
namespace Microsoft.SolverFoundation.Common
{
[CLSCompliant(true)]
public struct Rational : IComparable, IComparable<Rational>, IEquatable<Rational>, IComparable<BigInteger>, IEquatable<BigInteger>, IComparable<int>, IEquatable<int>, IComparable<uint>, IEquatable<uint>, IComparable<long>, IEquatable<long>, IComparable<ulong>, IEquatable<ulong>, IComparable<double>, IEquatable<double>
{
public static readonly Rational NegativeInfinity;
public static readonly Rational Zero;
public static readonly Rational One;
public static readonly Rational PositiveInfinity;
public static readonly Rational Indeterminate;
public static readonly Rational UnsignedInfinity;
public bool IsOne { get; }
public bool IsFinite { get; }
public bool IsIndeterminate { get; }
public bool IsInfinite { get; }
public bool IsSignedInfinity { get; }
public bool IsUnsignedInfinity { get; }
public bool HasSign { get; }
public bool IsNegativeInfinity { get; }
public bool IsZero { get; }
public int BitCount { get; }
public int Sign { get; }
public BigInteger Numerator { get; }
public bool IsPositiveInfinity { get; }
public BigInteger Denominator { get; }
public Rational AbsoluteValue { get; }
public static Rational AddMul(Rational ratAdd, Rational ratMul1, Rational ratMul2);
public static Rational Get(BigInteger bnNum, BigInteger bnDen);
public static void Negate(ref Rational num);
public static bool Power(Rational ratBase, Rational ratExp, out Rational ratRes);
public void AppendDecimalString(StringBuilder sb, int cchMax);
public int CompareTo(BigInteger bn);
[CLSCompliant(false)]
public int CompareTo(uint u);
public int CompareTo(Rational rat);
public int CompareTo(long nn);
[CLSCompliant(false)]
public int CompareTo(ulong uu);
public int CompareTo(double dbl);
public int CompareTo(int n);
public int CompareTo(object obj);
[CLSCompliant(false)]
public bool Equals(uint u);
public bool Equals(Rational rat);
public bool Equals(long nn);
[CLSCompliant(false)]
public bool Equals(ulong uu);
public bool Equals(int n);
public bool Equals(BigInteger bn);
public override bool Equals(object obj);
public bool Equals(double dbl);
public Rational GetCeiling();
public Rational GetCeilingResidual();
public Rational GetFloor();
public Rational GetFloorResidual();
public Rational GetFractionalPart();
public override int GetHashCode();
public Rational GetIntegerPart();
public double GetSignedDouble();
public Rational Invert();
public bool IsInteger(out BigInteger bn);
public bool IsInteger();
public double ToDouble();
public override string ToString();
public static Rational operator +(Rational rat1, Rational rat2);
public static Rational operator -(Rational rat);
public static Rational operator -(Rational rat1, Rational rat2);
public static Rational operator *(Rational rat1, Rational rat2);
public static Rational operator /(Rational rat1, Rational rat2);
[CLSCompliant(false)]
public static bool operator ==(uint n, Rational rat);
[CLSCompliant(false)]
public static bool operator ==(Rational rat, uint n);
public static bool operator ==(int n, Rational rat);
public static bool operator ==(long n, Rational rat);
public static bool operator ==(Rational rat, BigInteger bn);
public static bool operator ==(Rational rat, int n);
public static bool operator ==(Rational rat, long n);
public static bool operator ==(BigInteger bn, Rational rat);
public static bool operator ==(double dbl, Rational rat);
[CLSCompliant(false)]
public static bool operator ==(Rational rat, ulong n);
public static bool operator ==(Rational rat1, Rational rat2);
[CLSCompliant(false)]
public static bool operator ==(ulong n, Rational rat);
public static bool operator ==(Rational rat, double dbl);
[CLSCompliant(false)]
public static bool operator !=(ulong n, Rational rat);
[CLSCompliant(false)]
public static bool operator !=(Rational rat, ulong n);
[CLSCompliant(false)]
public static bool operator !=(uint n, Rational rat);
public static bool operator !=(BigInteger bn, Rational rat);
[CLSCompliant(false)]
public static bool operator !=(Rational rat, uint n);
public static bool operator !=(double dbl, Rational rat);
public static bool operator !=(int n, Rational rat);
public static bool operator !=(Rational rat, int n);
public static bool operator !=(long n, Rational rat);
public static bool operator !=(Rational rat, BigInteger bn);
public static bool operator !=(Rational rat1, Rational rat2);
public static bool operator !=(Rational rat, double dbl);
public static bool operator !=(Rational rat, long n);
public static bool operator <(double dbl, Rational rat);
public static bool operator <(Rational rat, double dbl);
[CLSCompliant(false)]
public static bool operator <(ulong n, Rational rat);
[CLSCompliant(false)]
public static bool operator <(Rational rat, ulong n);
[CLSCompliant(false)]
public static bool operator <(uint n, Rational rat);
public static bool operator <(Rational rat1, Rational rat2);
public static bool operator <(Rational rat, BigInteger bn);
public static bool operator <(long n, Rational rat);
public static bool operator <(BigInteger bn, Rational rat);
public static bool operator <(Rational rat, int n);
public static bool operator <(int n, Rational rat);
[CLSCompliant(false)]
public static bool operator <(Rational rat, uint n);
public static bool operator <(Rational rat, long n);
public static bool operator >(long n, Rational rat);
public static bool operator >(Rational rat1, Rational rat2);
public static bool operator >(Rational rat, BigInteger bn);
public static bool operator >(BigInteger bn, Rational rat);
public static bool operator >(Rational rat, int n);
[CLSCompliant(false)]
public static bool operator >(Rational rat, uint n);
public static bool operator >(double dbl, Rational rat);
[CLSCompliant(false)]
public static bool operator >(uint n, Rational rat);
public static bool operator >(int n, Rational rat);
public static bool operator >(Rational rat, long n);
public static bool operator >(Rational rat, double dbl);
[CLSCompliant(false)]
public static bool operator >(ulong n, Rational rat);
[CLSCompliant(false)]
public static bool operator >(Rational rat, ulong n);
[CLSCompliant(false)]
public static bool operator <=(ulong n, Rational rat);
public static bool operator <=(Rational rat, int n);
public static bool operator <=(Rational rat, BigInteger bn);
public static bool operator <=(int n, Rational rat);
[CLSCompliant(false)]
public static bool operator <=(Rational rat, uint n);
public static bool operator <=(BigInteger bn, Rational rat);
[CLSCompliant(false)]
public static bool operator <=(Rational rat, ulong n);
public static bool operator <=(Rational rat1, Rational rat2);
public static bool operator <=(long n, Rational rat);
public static bool operator <=(Rational rat, double dbl);
public static bool operator <=(double dbl, Rational rat);
[CLSCompliant(false)]
public static bool operator <=(uint n, Rational rat);
public static bool operator <=(Rational rat, long n);
public static bool operator >=(Rational rat, BigInteger bn);
public static bool operator >=(Rational rat1, Rational rat2);
[CLSCompliant(false)]
public static bool operator >=(Rational rat, ulong n);
[CLSCompliant(false)]
public static bool operator >=(uint n, Rational rat);
public static bool operator >=(Rational rat, long n);
public static bool operator >=(int n, Rational rat);
public static bool operator >=(BigInteger bn, Rational rat);
public static bool operator >=(Rational rat, int n);
[CLSCompliant(false)]
public static bool operator >=(ulong n, Rational rat);
public static bool operator >=(long n, Rational rat);
public static bool operator >=(double dbl, Rational rat);
[CLSCompliant(false)]
public static bool operator >=(Rational rat, uint n);
public static bool operator >=(Rational rat, double dbl);
public static implicit operator Rational(double dbl);
public static implicit operator Rational(BigInteger bn);
[CLSCompliant(false)]
public static implicit operator Rational(uint u);
public static implicit operator Rational(long nn);
[CLSCompliant(false)]
public static implicit operator Rational(ulong uu);
public static implicit operator Rational(int n);
public static explicit operator BigInteger(Rational rat);
public static explicit operator double(Rational rat);
[CLSCompliant(false)]
public static explicit operator ulong(Rational rat);
public static explicit operator long(Rational rat);
[CLSCompliant(false)]
public static explicit operator uint(Rational rat);
public static explicit operator int(Rational rat);
}
}
The other very useful bit of information that can be found at the above link is this table:
"The following table lists how special cases of rational numbers are represented.
Rational number
Representation
Non-zero finite rational values
(numerator, denominator) with denominator > 0
Zero
(0, 0)
Negative infinity
(-1, 0)
Positive infinity
(+1, 0)
Unsigned infinity
(+2, 0)
Indeterminate (NaN)
(+3, 0)
Dividing a nonzero value by zero results in unsigned infinity because 0 is unsigned. Dividing a finite value by any infinite value results in 0."

jna: pass a string from C# to Java

I am using Unamanged dependencies (RGiesecke.DllExport.DllExport) and jna in a small C# function that should return a string consumed within another now java function.
Following the jna suggestions for mapping i crafted the code below:
My C# code:
[RGiesecke.DllExport.DllExport]
public static unsafe char* Test(string id)
{
unsafe
{
fixed (char *s = "test passed")
{
return s;
}
}
}
Java side:
public interface ITest extends Library{
public String Test(String id);
}
public static void main(String[] args) {
ITest nativeExample= (ITest)Native.loadLibrary("C:/native/JavaLib.dll", ITest.class);
String s = nativeExample.Test("id");
System.out.println(s);
}
So, all that is printed, is 't', because I bet all is being transmitted is the address to s[0].
Has anyone had luck mapping strings from C# to java through jna?
Plain strings in the C# code throws errors.
Have you tried returning a string instead of char? or changing char *s to char s[]

How to escape asterisk in me.regexp

I have a regex that looks like this:
RE regex = new RE("([TtYy\\*])(?:([+-])([\\d]+)([dDmMhH]))?");
It is supposed to match
*-30m
T-60h
T
Y
and so on.
but the escape on the asterisks is not working. I tried a few combinations like single slash, grouping that sequence with parenthesis. Anyone have ideas?
I am using me.regexp from http://code.google.com/p/regexp-me/
In me.regexp.RE.java there are doc comments:
The full regular expression syntax accepted by RE is described here:
Characters
unicodeChar - Matches any identical unicode character
\ - Used to quote a meta-character (like '*')
\\ - Matches a single '\' character
\0nnn - Matches a given octal character
\xhh - Matches a given 8-bit hexadecimal character
So single backslash should work here, or there is an issue in lib.
UPDATE
I have tried pattern "([TtYy\*])(?:([+-])([\d]+)([dDmMhH]))?" and text "*-30m" and it works perfectly for my 8900 simulator on RIM 5.0
See code:
public final class MyScreen extends MainScreen
implements FieldChangeListener {
static final int INT_MAX_LEN = 200;
static final String STR_PATTERN = "Pattern:";
static final String STR_TEXT = "Text:";
static final String STR_RESULT = "Result:";
static final String STR_RUN_TEST = "Run test";
static final String STR_DEFAULT_PATTERN =
"([TtYy\\*])(?:([+-])([\\d]+)([dDmMhH]))?";
static final String STR_DEFAULT_TEXT = "*-30m";
EditField mPattern = new EditField(STR_PATTERN, STR_DEFAULT_PATTERN,
INT_MAX_LEN, Field.USE_ALL_WIDTH);
EditField mText = new EditField(STR_TEXT, STR_DEFAULT_TEXT, INT_MAX_LEN,
Field.USE_ALL_WIDTH);
LabelField mResult = new LabelField(STR_RESULT, Field.USE_ALL_WIDTH);
ButtonField mBtnRunTest =
new ButtonField(STR_RUN_TEST, Field.USE_ALL_WIDTH
| ButtonField.CONSUME_CLICK);
public MyScreen() {
add(mPattern);
add(mText);
add(mResult);
add(mBtnRunTest);
mBtnRunTest.setChangeListener(this);
}
public void fieldChanged(Field field, int context) {
if (field == mBtnRunTest) {
runTest();
}
}
private void runTest() {
RE regex = new RE(mPattern.getText());
String result = regex.match(mText.getText()) ? "TRUE" : "FALSE";
mResult.setText(STR_RESULT + result);
}
}

Resources