possible to define a function in commandline window of a programming language?
Is it possible to define a function in commandline window of Matlab? Looks no to me.
But for R, it is开发者_如何学JAVA possible to do so. I was wondering why there is this difference and if there is more to say behind this kind of feature of a programming language, or can I say just interpretive language (such as Python, Bash,...)?
Thanks!
You can define functions in the command window of Matlab. It will be evaluated like a function, but it won't be available to you in your next Matlab session (though you can save and load it like a variable).
As an example, I copy @Dirk Eddelbuettel's function
>> cubed = @(x)x^3;
>> cubed(2)
ans =
8
EDIT 1
Note that you can only define single-statement functions as anonymous functions in Matlab, so you can't use e.g. for-loops (unless you use evil eval
, which allows everything). However, if you nest anonymous functions, you can create arbitrarily complicated recursive statements. Thus, I guess that you can indeed define any function in the command line window. It might just not be worth the effort, and I bet that it'll be very difficult to understand.
EDIT 2 Here's an example of a recursive nested anonymous function to calculate factorials from Matlab central:
>> fact = @(val,branchFcns) val*branchFcns{(val <= 1)+1}(val-1,branchFcns);
>> returnOne = @(val,branchFcns) 1;
>> branchFcns = {fact returnOne};
>> fact(4,branchFcns)
ans =
24
>> fact(5,branchFcns)
ans =
120
This isn't really a feature of a programming language but of an implementation of that programming language. For example, there exist C interpreters and Lisp Compilers. This is normaly called an REPL (Read-Eval-Print-Loop) and is generally a feature of interpreted implementations.
Yes, if and when the language at hand supports it. So here is a trivial R example, cut and pasted from the command-prompt I am using:
R> cubed <- function(x) x^3
R> cubed(2)
[1] 8
R> cubed(3)
[1] 27
R>
精彩评论