Changing Access modifier using reflection in kotlin - reflection

I know in java if I wish to use reflection to set a final field I can change the access modifier of the field like so:
Field field = clazz.getDeclaredField("someField");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
I am have difficulty achieving the same thing in kotlin. The problem is with the bitwise operators on the final line modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL). Admittedly I am somewhat ignorant of bitwise operators in general and do not know the kotlin equivalents.

Immediately after posting the question I found the solution. The bitwise operators that are being used and their java representations are AND ($) and bitwise compliment (~).
In kotlin the AND bitwise operator is an infix function of the Int class and. Similarly the bitwise compliment operator is also a function, inv, on the Int class.
The way to change the modifier in kotlin is:
val field = clazz.getDeclaredField("someField")
field.isAccessible = true
val modifers = field.javaClass.getDeclaredField("modifiers")
modifers.isAccessible = true
modifers.setInt(field, field.modifiers and Modifier.FINAL.inv())

Related

Why can't a range of char be collected?

I'm trying to generate a vector containing lowercase ASCII characters. This more convoluted approach works:
let ascii_lowercase = (b'a'..=b'z').map(|b| b as char).collect::<Vec<char>>();
But this more straightforward one, which I came up with in the first place, does not:
let ascii_lowercase = ('a'..='z').collect::<Vec<char>>();
The error is:
error[E0599]: no method named `collect` found for type `std::ops::RangeInclusive<char>` in the current scope
--> src/main.rs:2:39
|
2 | let ascii_lowercase = ('a'..='z').collect::<Vec<char>>();
| ^^^^^^^
|
= note: the method `collect` exists but the following trait bounds were not satisfied:
`std::ops::RangeInclusive<char> : std::iter::Iterator`
`&mut std::ops::RangeInclusive<char> : std::iter::Iterator`
Which is weird, because as far as I understand, there is a blanket implementation of Iterator for RangeInclusive.
Is it impossible to use a range of chars as an iterator? If so, why? If not, what am I doing wrong? I'm using stable Rust 2018 1.31.1.
EDIT 2020-07-17: since Rust 1.45.0, the trait Step is implemented for char, making Range<char> (and some other char ranges) work as an iterator. The code in the question now compiles without problem!
Old answer below.
The expression b'a'..=b'z' has the type RangeInclusive<u8> (see on Playground) because the expression b'a' has the type u8: that's what the b in front of the character literal is for. On the other hand, the expression 'a'..='z' (without the bs) has the type RangeInclusive<char>.
[...] there is a blanket implementation of Iterator for RangeInclusive.
For one, this is not what we call "blanket implementation" (this is when the impl block is for T or for &T (or similar) with T being a generic type). But yes, there is an impl. But let's take a closer look:
impl<A> Iterator for RangeInclusive<A>
where
A: Step, // <--- important
The A: Step bound is important. As you can see in the documentation for Step, this trait is implemented for all primitive integer types, but not for char. This means that there is no clear "add one" operation on characters. Yes, you could define it to be the next valid Unicode codepoint, but the Rust developers probably decided against that for a good reason.
As a consequence, RangeInclusive<char> does not implement Iterator.
So your solution is already a good one. I would probably write this:
(b'a'..=b'z').map(char::from).collect::<Vec<_>>()
The only real advantage is that in this version, char doesn't appear twice.
The problem was that the iteration capabilities of range types depend on the Step trait (see extended answer).
However, starting from Rust 1.45, char also implements Step (PR 72413), which means that the code in the question now works!
let ascii_lowercase: Vec<char> = ('a'..='h').collect();
assert_eq!(
ascii_lowercase,
vec!['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
);

In julia functions : passed by reference or value?

In julia how do we know if a type is manipulated by value or by reference?
In java for example (at least for the sdk):
the basic types (those that have names starting with lower case letters, like "int") are manipulated by value
Objects (those that have names starting with capital letters, like "HashMap") and arrays are manipulated by reference
It is therefore easy to know what happens to a type modified inside a function.
I am pretty sure my question is a duplicate but I can't find the dup...
EDIT
This code :
function modifyArray(a::Array{ASCIIString,1})
push!(a, "chocolate")
end
function modifyInt(i::Int)
i += 7
end
myarray = ["alice", "bob"]
modifyArray(myarray)
#show myarray
myint = 1
modifyInt(myint)
#show myint
returns :
myarray = ASCIIString["alice","bob", "chocolate"]
myint = 1
which was a bit confusing to me, and the reason why I submitted this question. The comment of #StefanKarpinski clarified the issue.
My confusion came from the fact i considred += as an operator , a method like push! which is modifying the object itself . but it is not.
i += 7 should be seen as i = i + 7 ( a binding to a different object ). Indeed this behavior will be the same for modifyArray if I use for example a = ["chocolate"].
The corresponding terms in Julia are mutable and immutable types:
immutable objects (either bitstypes, such as Int or composite types declared with immutable, such as Complex) cannot be modified once created, and so are passed by copying.
mutable objects (arrays, or composite types declared with type) are passed by reference, so can be modified by calling functions. By convention such functions end with an exclamation mark (e.g., sort!), but this is not enforced by the language.
Note however that an immutable object can contain a mutable object, which can still be modified by a function.
This is explained in more detail in the FAQ.
I think the most rigourous answer is the one in
Julia function argument by reference
Strictly speaking, Julia is not "call-by-reference" but "call-by-value where the value is a
reference" , or "call-by-sharing", as used by most languages such as
python, java, ruby...

Trying to understand the SML option structure

Okay so I started learning SML for a class, and I'm stuck with the option structure.
What I have so far for this example:
datatype suit = spades|hearts|clubs|diamonds;
datatype rank = ace|two|three|...|j|q|k|joker;
type card = suit*rank;
My lecturer was trying to explain the use of the option structure by saying that not all cards necessarily have a suit; jokers don't have a suit associated with them.
So when designing a function getsuit to get the suit of a card, we have the following:
datatype 'a option = NONE | SOME of 'a;
fun getsuit ((joker,_):card):suit option = NONE
| getsuit ((_,s):card):suit option = SOME s;
But using emacs, I get two errors, one saying how the pattern and constraint don't agree,
pattern: rank * ?.suit
constraint: rank * suit
and the other saying how the expression type and the resulting types don't agree.
expression: ?.suit option
result type: suit option
This was the code provided by the lecturer so clearly they're not of much help if it results in errors.
What's the meaning of "?." and why does it show up? How would I correctly define this function?
Not really a problem with option as you've defined it.
You've got the order of suit and rank in your card patterns the wrong way:
Try:
datatype 'a option = NONE | SOME of 'a;
fun getsuit ((_, joker):card):suit option = NONE
| getsuit ((s, _):card):suit option = SOME s;
My version of ML probably prints errors differently so I'm not sure how to explain the the meaning of ?. etc. But it's simple enough if you take it bit by bit:
Try
(clubs, ace);
The interpreter (or emacs if that's what you're using) tells you the type is a product of a suit * rank. That's ML's type inference at work, but you can specify the type (you expect) like this:
(clubs, ace): suit*rank;
Or
(clubs, ace): card; (* Works, since card is defined as (suit*rank) *)
And you won't have any complaints. But obviously you would if you did
(clubs, ace): rank*suit;
Or
(clubs, ace): card; (* card is defined as (rank*) *)
You placed a constraint on the type of getsuit's argument (that it must be a card, or the compatible (suit*rank) product), but the pattern is of type (rank*?) or (?*rank), neither of which are compatible with (suit*rank).

Evaluating Postfix Notation

I wrote a stack class to evaluate a postfix expression. I understand how to do it except for the order of it. Let's say I have a simple one like:
A B - C +
My only question is, would it be A - B, or B - A? I can't find any resource online that explains that part of evaluation.
Your operators are just functions. So you can define those functions however you want.
I personally would define - to take two arguments, and subtract the second from the first. This would be consistent with most people's expectations, and also how existing RPN calculators work. See, for instance, http://h41111.www4.hp.com/calculators/uk/en/articles/rpn.html for more on that.
Simple ES6 implementation:
const postfix = input => input.split(' ').reduce((result, token) =>
isNaN(token)
? [ eval(`${result.shift()}${token}${result.shift()}`), ...result ]
: [ token, ...result ]
, [])[0];

generic duck typing in F#?

using let inline and member constraints I'll be able to make duck typing for known members but what if I would like to define a generic function like so:
let duckwrapper<'a> duck = ...
with the signature 'b -> 'a and where the returned value would be an object that implemented 'a (which would be an interface) and forwarded the calls to duck.
I've done this in C# using Reflection.Emit but I'm wondering if F# reflection, quotations or other constructs would make it easier.
Any suggestions on how to accomplish this?
EDIT
after reading Tims answer I thought I'd give a bit more details
What I was thinking of when I wrote about using quotations to help was something like:
{new IInterface with member x.SayHello() = !!<# %expr #>}
!! being an operator translating the quotation to a function and %expr being the unit of work for the method. I'd be able to translate the expression to a function (I guess) but wouldn't know how to
of course this wouldn't do the trick completely either since IInterface would be 'a which is where I hope F# reflection might have some handy functions so that I could construct a type based on a type object and some function values
EDIT
As an update to Tomas Petricek answer I'll give some code to explain my needs
type SourceRole =
abstract transfer : decimal -> context
and context(sourceAccount:account, destinationAccount) =
let source = sourceAccount
let destination = destinationAccount
member self.transfer amount =
let sourcePlayer =
{new SourceRole with
member this.transfer amount =
use scope = new TransactionScope()
let source = source.decreaseBalance amount
let destination = destination.increaseBalance amount
scope.Complete()
context(source,destination)
}
sourcePlayer.transfer(amount)
which is a try at porting "the" textbook example of DCI in F#. The source and destination are DCI roles. It's the idea that any data object that adhere's to a specific contract can play those. In this case the contract is simple. source needs a memberfunction called decreaseBalance and destination needs a member function called increaseBalance.
I can accomplish that for this specific case with let inline and member constraints.
But I'd like to write a set of functions that given an interface and an object. In this case it could be source (as the object) and
type sourceContract =
abstract decreaseBalance : decimal -> sourceContract
as the type. The result would be an object of type sourceContract that would pipe method calls to a method with the same name on the source object.
F# reflection (Microsoft.FSharp.Reflection) is an F#-friendly wrapper around the plain System.Reflection APIs, so I don't think it would add anything here.
Quotations can't define new types: (you'd need to define a new type to do your interface-based duck typing)
> <# { new IInterface with member x.SayHello = "hello" } #>;;
<# { new IInterface with member x.SayHello = "hello" } #>;;
---^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
stdin(7,4): error FS0449: Quotations cannot contain object expressions
> <# type Test() = class end #>;;
<# type Test() = class end #>;;
---^^^^
stdin(8,4): error FS0010: Unexpected keyword 'type' in quotation literal
Reflection.Emit is still the way to go with this.
Edit:
I hope F# reflection might have some handy functions so that I could construct a type based on a type object and some function values
I'm afraid it doesn't. Here's the documentation on F# reflection: http://msdn.microsoft.com/en-gb/library/ee353491.aspx
You can compile F# quotations using components from F# PowerPack. So I think you could use quotations to generate and execute code at runtime. If you write a quotation representing a function & compile it you'll get a function value that you could use to implement an interface. Here is a trivial example:
#r "FSharp.PowerPack.Linq.dll"
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Linq.QuotationEvaluation
// Create a part using "Expr." calls explicitly
let expr = Expr.Value(13)
// Create a part using quotation syntax
let expr2 = <# (fun x -> x * %%expr) #>
// Compile & Run
let f = expr2.Compile()()
f 10
You can mix quotation syntax and calls to Expr, which makes it easier to compose code from basic blocks. The compilation is a bit stupid (currently) so the generated code won't be as efficient as usual F# code (but you'll need to measure it in your case).
I'm not quite sure I understand what exactly are you trying to do, so if you can provide more details, I can give more specific answer.

Resources