i'm trying to do an "node" Class in R, like in java:
but the code pop up an error, "The class node doesn't exist when i'm creating the value "Next="node"
is it not possible to do recursion in a class in R? or how could i do this?
node <- setRefClass("node", fields = list(value="numeric", next="node"))
Error: inesperado '=' in "node <- node <- setRefClass("node", fields = list(value="numeric", next=""
The problem here is that you are using the flow Control word next. Try help(next) and this description comes up
These are the basic control-flow constructs of the R language. They function in much the same way as control statements in any Algol-like language. They are all reserved words.
As such they cannot be used for variable names, and if they are used for list names they should be quoted. Eg. this will work:
setRefClass('node', fields = list(value = 'numeric', 'next' = 'node'))
note that I wrote 'next' and not next
As a side note I would suggest checking out the R6 package, which provides a simpler interface to OOP than reference classes while also being much faster than reference classes.
Related
From their quickstart guide I got this following sample
alert cpu.is.too.high {
template = test
$metric = q("sum:rate{counter,,1}:os.cpu{host=your-system-here}", "1h", "")
$avgcpu = avg($metric)
crit = $avgcpu > 80
warn = $avgcpu > 60
}
I would guess it's a perlish DSL. What is the name of this language?
We just call it "Bosun's expression language" and is documented at http://bosun.org/expressions.html. As you said it is a custom DSL. It currently has the following qualities
It is not imperative. The language itself actually lacks true variables, the "$foo" are just text replacement
It is functional
It is well typed (functions accept and return specific types. Since the DSL is for alerting, we believe it is important to catch as many errors at possible at parse time.)
The guts implementation of the parser and lexer is based on that guts of text/template. A map function that takes an expression to operator on every X item in a series for an entire seriesSet is in the works, so the language is still a bit in the works. But I don't think we will be change the underlying design choices mentioned above (except maybe actually use real variables instead of text replacement at some point.)
I have created an S4 class ("card") that resembles a record with several fields. Now I want to define a collection class ("cat") to hold many "card" objects. The cat class will include methods for searching, editing, and adding cards.
Here is a simplified version of what I'm trying to create:
Card <- setClass("Card",
representation(dsOwner = "character", dsFile = "character", dsUrl = "character"))
Cat <- setClass("Cat", representation(cardlist = "list"))
setGeneric("addcard",
function(catObj, owner, file, url)
standardGeneric("addcard"))
setMethod("addcard",
signature(catObj = "Cat"),
function(catObj, owner, file, url){
index <- length(catObj) + 1
catObj[[index]] <- new("Card",
dsOwner = owner,
dsFile = file,
dsUrl = url)
return(index)
})
catalog <- new("Cat")
addcard(catalog, owner = "some online resource", file = "some file name", url = "http://some.url")
Unfortunately, executing the addcard method throws an error I don't understand:
Error in '[[<-'('*tmp*`, index, value = <S4 object of class "Card">) :
[[<- defined for objects of type "S4" only for subclasses of environment'.
Did I not define the cat class correctly?
R does not have a coherent java/C++-like container support to handle arrays, lists, sets, maps, etc (in OOP sense.)
R vectors/lists are in many ways similar to java lists/c++ arrays. I don't know much about speed and efficiency though, I suspect R does many more copies unlike java/c++
Simple set functions with vectors can be done by union, setdiff, unique etc functions. There is also library "sets" that handled very well the simple objects I throw to it.
named vectors (including named lists) are in many ways like a maps. The key is the name, and with some tricks you can make a string key out of any type of object. I suspect though these are not hashed, and the performance seems not to be good. You can also implement maps via environment (see Natural way to represent hash tables/dictionaries/maps in R) and data.table (Dictionaries and pairs in R)
Usually you get pretty far by using these simple measures but I would love to see a more rigorous and efficient implementation. I would happy to be wrong though :-)
I am trying to build a package that contains own S4 class definitions. R check works but issues the following warning: undefined slot classes in definition mySecond.
I set to classes while one slot in the second class is of class myFirstClass. E.g.:
setClass("myFirst",representation(field_one = "character",
field_two = "list")
)
setClass("mySecond",representation(a = "character",
b = "myFirst")
)
Note:Though S4 might be easier to handle I'd like to stick to S4 here, because I am mapping information from a database and prefer S4's stricter definitions in this case. The compilation does work but I try to fulfill CRAN's standards here and want to get rid of the warnings. Btw:
getClassDef gives reasonable result for both classes.
Maybe your class definitions are in separate files, and the collation is such that mySecond is defined before myFirst? See the Collate: field in DESCRIPTION (Section 1.1.1 of RShowDoc("R-exts"), or follow one model of structuring packages where a file AllClasses.R contains class definitions.
I need to use eval to call a reference class method. Below is a toy example:
MyClass <- setRefClass("MyClass",
fields = c("my_field"),
methods = list(
initialize = function(){
my_field <<- 3
},
hello = function(){
"hello"
},
run = function(user_defined_text){
eval(parse(text = user_defined_text))
}
)
)
p <- MyClass$new()
p$run("hello()") # Error: could not find function "hello" - doesn't work
p$run(".self$hello()") # "hello" - it works
p$run("hello()") # "hello" - now it works?!
p <- MyClass$new()
p$run("my_field") # 3 - no need to add .self
I guess I could do eval(parse(text = paste0(".self$", user_defined_text))), but I don't really understand:
why is .self needed to eval methods, but not fields?
why is .self no longer needed after it has been used once?
'Why' questions are always challenging to answer; usually the answer is 'because'. On ?setRefClass we eventually have
Only methods actually used will be included in the environment
corresponding to an individual object. To declare that a method
requires a particular other method, the first method should
include a call to '$usingMethods()' with the name of the other
method as an argument. Declaring the methods this way is essential
if the other method is used indirectly (e.g., via 'sapply()' or
'do.call()'). If it is called directly, code analysis will find
it. Declaring the method is harmless in any case, however, and may
aid readability of the source code.
I'm not sure this is entirely helpful in your case, where the user is apparently able to specify any method. Offering a little unasked editorial comment, I'm not sure 'why' you'd want to write a method that would parse input text to methods; I've never used that paradigm myself.
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.