Is there a reduce() list method in Specman that I can use for general reduction functions? I'm thinking of something like:
var x: list of bit = some_function_that_returns_list_of_bit;
var bitmap: uint = x.reduce(foo());
where reduce() works like in Python:
foo(last: uint, val: bit) is: uint {
return (last << 1 ) | bit;
};
Specman 6.1 docs don't show a reduce pseudo-method. For your specific example, you can acheive what you want with:
bitmap = pack(packing.low, x)
You may find the "reduce" psuedo-method in your version of Specman by searching "List Pseudo-Methods" in your docs.
Section "Math and Logic Pseudo-Methods" shows methods and_all(), average(), or_all(), product(), and sum(). I know this is not the meta-solution, but its better than a kick in the teeth.
Related
I will be using JavaScript to demonstrate my example, but the question remains open to other programming languages as well.
Let's consider a simple recursive function:
function f(x){
if(x>1) return f(x-1)+5;
else return 3;
}
Let's say I want to display the value of the function for all x from 1 to 5, where x is an integer. The most obvious solution would be the following:
for(i=1; i<=5; i++){
console.log(f(i));
}
This method, however, seems incredibly inefficient, as we are calling the function 5+4+3+2+1 times. Intuitively, only 5 function calls would be necessary, as whenever we want the value of f(5), it is necessary to find the value of f(4) f(3) f(2) and f(1) first, so after finding f(5), we wouldn't need to call f(4) and start the entire process all over again to just to find the value of f(4) which we already found once.
Any ideas?
I would like to log plot a function in Julia.
using Plots
x = 1:100
plot(x.^2, xaxis=:log)
I used the same logic as the working code from above but I got following error:
My guess is that I need to "transform" the function into a unit range (if that makes any sense). However, I am not sure how to do that.
using Plots
function test(a)
alpha = 1
for i in 1:a
alpha += 1
end
return alpha
end
a = 1:100
plot(test(a), xaxis=:log)
MethodError: no method matching (::Colon)(::Int64, ::UnitRange{Int64})
You need to broadcast test like this:
plot(test.(a), xaxis=:log)
(note a . after test)
Alternatively plot is smart enough to know how to plot a function just like this:
plot(test, 1, 100, xaxis=:log)
See here for more examples.
Disclaimer: I have almost no mathematics notions, so this question could be very basic for some of you.
I'm searching for the name of a concept which consists in combining pure functions together (say, functions with the same input and output types and number of parameters) to make them simpler.
Suppose I have these 3 methods with the same signature:
addOne(param: number): number {
return param + 1;
}
addTwo(param: number): number {
return param + 2;
}
multiplyByThree(param: number): number {
return param * 3;
}
Now I know that I'll always use these functions in the same order and same param.
Ex: I will process a sound or an image.
I want to avoid uselessly applying coefficient or offsets that could be computed together (optimization/regression).
Let's say I have this imaginary library with a method called computeOptimizedFunction that applies this concept to my functions. It takes any number of functions with the same signature as input.
var optimized = computeOptimizedFunction(addOne, addTwo, multiplyByThree);
Actually equals to:
var optimized = (param: number) => 3 * (param + 3);
Anyone here has an idea of how this concept or pattern is called, if it exists?
If the let keyword introduces a proper implementation of block scope, does var any longer have a use case? I am looking at this from a software design standpoint rather than a syntactical, "well you could" standpoint.
If the let keyword introduces a proper implementation of block scope, does var any longer have a use case?
There could be one use case: let declarations in global scope don't create a property on the global object. Example:
"use strict"; // for chrome
var foo = 42;
let bar = 21;
console.log('window.foo (var)', window.foo); // 42
console.log('window.bar (let)', window.bar); // undefined
From 8.1.1.4 Global Environment Records
The object Environment Record component of a global Environment Record contains the bindings for all built-in globals (clause 18) and all bindings introduced by a FunctionDeclaration, GeneratorDeclaration, or VariableStatement contained in global code. The bindings for all other ECMAScript declarations in global code are contained in the declarative Environment Record component of the global Environment Record.
However, this can also easily be solved by creating an explicit global variable using by assigning to the global object directly:
window.foo = 42;
This would also be the only way to create global classes btw, because the class declaration has the same behavior.
(Note: I'm not advocating the use of global variables)
There are syntax constructs where you can only use var, but that's more a consequence of the how the spec evolved and doesn't really serve any practical purpose. For example:
if (true)
var foo = 42; // valid but kind of useless or bad design
// vs
if (true)
let foo = 42; // invalid
Block scope is not the only useful feature though. The temporal dead zone is another handy feature to find bugs more easily. Compare:
var foo = 42;
function bar() {
console.log(foo); // undefined
var foo = 21;
}
bar();
// vs
var foo = 42; // or `let`, doesn't matter
function bar() {
console.log(foo); // ReferenceError, temporal dead zone
let foo = 21;
}
bar();
You get a reference error when trying to access a let variable that wasn't initialized yet.
let can't be used in global scope yet. var can.
This is what you get from Chrome when you try a global let outside of strict mode:
Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
Practically there may be some use-cases.
1. Declare variable in try-catch like so:
try {
//inits/checks code etc
let id = getId(obj);
var result = getResult(id);
} catch (e) {
handleException(e);
}
//use `result`
With let the result declaration would be before try, - a bit early and out of context.
2. Same for conditional declarations:
if (opts.re) {
var re = new RegExp(opts.re);
var result = match(re);
if (!result) return false;
}
// result is available here
With let this code would be forced to complain "good style", though that might be impractical.
3. Loop block:
for (var x = 0; x < data.width; x++) {
if (data[x] == null) break;
//some drawing/other code
}
//`x` pointing to the end of data
Some may consider that untidy, I myself prefer lets, but if code I already has vars - that's natural to keep using them.
You can use var if you want to deconstruct something into the function scope, for example a conditional:
if (Math.random() > 0.5)
var {a,b} = {a: 1, b: 2}
else
var {a,b} = {a: 10, b: 20}
// Some common logic on a and b
console.log(a, b)
With let you would have to write something like
let result;
if (Math.random() > 0.5)
result = {a: 'foo', b: 'bar'}
else
result = {a: 'baz', b: 'qux'}
// Using const might make more sense here
let {a, b} = result;
// Some common logic on a and b
console.log(a,b)
Don't Throw Out var
Stylistically, var has always, from the earliest days of JS, signaled "variable that belongs to a whole function." var attaches to the nearest enclosing function scope, no matter where it appears. That's true even if var appears inside a block:
function diff(x,y) {
if (x > y) {
var tmp = x; // `tmp` is function-scoped
x = y;
y = tmp;
}
return y - x;
}
Even though var is inside a block, its declaration is function-scoped (to diff(..)), not block-scoped.
While you can declare var inside a block (and still have it be function-scoped), I would recommend against this approach except in a few specific cases. Otherwise, var should be reserved for use in the top-level scope of a function.
Why not just use let in that same location? Because var is visually distinct from let and therefore signals clearly, "this variable is function-scoped." Using let in the top-level scope, especially if not in the first few lines of a function, and when all the other declarations in blocks use let, does not visually draw attention to the difference with the function-scoped declaration.
In other words, I feel var better communicates function-scoped than let does, and let both communicates (and achieves!) block-scoping where var is insufficient. As long as your programs are going to need both function-scoped and block-scoped variables, the most sensible and readable approach is to use both var and let together, each for their own best purpose.
There are also other semantic and operational reasons to choose var or let in different scenarios.
WARNING:
My recommendation to use both var and let is clearly controversial and contradicts the majority. It's far more common to hear assertions like, "var is broken, let fixes it" and, "never use var, let is the replacement." Those opinions are valid, but they're merely opinions, just like mine. var is not factually broken or deprecated; it has worked since early JS and it will continue to work as long as JS is around.
Where To let?
My advice to reserve var for (mostly) only a top-level function scope means that most other declarations should use let. But you may still be wondering how to decide where each declaration in your program belongs?
POLE already guides you on those decisions, but let's make sure we explicitly state it. The way to decide is not based on which keyword you want to use. The way to decide is to ask, "What is the most minimal scope exposure that's sufficient for this variable?"
Once that is answered, you'll know if a variable belongs in a block scope or the function scope. If you decide initially that a variable should be block-scoped, and later realize it needs to be elevated to be function-scoped, then that dictates a change not only in the location of that variable's declaration, but also the declarator keyword used. The decision-making process really should proceed like that.
If a declaration belongs in a block scope, use let. If it belongs in the function scope, use var (again, just my opinion).
Why use var for function scoping? Because that's exactly what var does. There literally is no better tool for the job of function scoping a declaration than a declarator that has, for 25 years, done exactly that.
You could use let in this top-level scope, but it's not the best tool for that job. I also find that if you use let everywhere, then it's less obvious which declarations are designed to be localized and which ones are intended to be used throughout the function.
By contrast, I rarely use a var inside a block. That's what let is for. Use the best tool for the job. If you see a let, it tells you that you're dealing with a localized declaration. If you see var, it tells you that you're dealing with a function-wide declaration. Simple as that.
function getStudents(data) {
var studentRecords = [];
for (let record of data.records) {
let id = `student-${ record.id }`;
studentRecords.push({
id,
record.name
});
}
return studentRecords;
}
The studentRecords variable is intended for use across the whole function. var is the best declarator to tell the reader that. By contrast, record and id are intended for use only in the narrower scope of the loop iteration, so let is the best tool for that job.
In addition to this best tool semantic argument, var has a few other characteristics that, in certain limited circumstances, make it more powerful.
One example is when a loop is exclusively using a variable, but its conditional clause cannot see block-scoped declarations inside the iteration:
function commitAction() {
do {
let result = commit();
var done = result && result.code == 1;
} while (!done);
}
Here, result is clearly only used inside the block, so we use let. But done is a bit different. It's only useful for the loop, but the while clause cannot see let declarations that appear inside the loop. So we compromise and use var, so that done is hoisted to the outer scope where it can be seen.
The alternative—declaring done outside the loop—separates it from where it's first used, and either necessitates picking a default value to assign, or worse, leaving it unassigned and thus looking ambiguous to the reader. I think var inside the loop is preferable here.
There are other nuances and scenarios when var turns out to offer some assistance, but I'm not going to belabor the point any further. The takeaway is that var can be useful in our programs alongside let (and the occasional const). Are you willing to creatively use the tools the JS language provides to tell a richer story to your readers?
Don't just throw away a useful tool like var because someone shamed you into thinking it wasn't cool anymore. Don't avoid var because you got confused once years ago. Learn these tools and use them each for what they're best at.
Source: YDKJS by Kyle Simpson
So, I was just thinking about how cool chaining is and how it makes things easier to read. With a lot of languages, when applying a bunch of functions to a variable, you'd write something like this:
i(h(g(f(x))))
And you have to read it from right-to-left or inner-most to outer-most. You apply f first, then g, and so forth. But if it were chained, it would look more like
x|f|g|h|i
And you could read it like a normal human being. So, my question is, there has to be some languages that do it that way, what are they? Is that what these fancy-pants functional programming languages do?
Because of this, I usually end up creating a whole bunch of temp variables so that I can split it onto separate lines and make it more readable:
a = f(x)
b = g(a)
c = h(b)
what_i_really_wanted_all_along = i(c)
Where's with my magical language, you could still split it onto different lines, if they're getting too long, without needing intervening variables:
x | f
| g
| h
| i
Yes, with F# you have a pipeline operator |> (also called forward pipe operator, and you have a backward pipe <|).
You write it like: x |> f |> g |> h |> i
Check this blog post that gives a good idea of real life usage.
It's not exclusive to functional programming, though it probably best implemented in functional languages, since the whole concept of function composition is squarely in the functional programming's domain.
For one thing, any language with object-oriented bent has chaining for methods which return an instance of the class:
obj.method1().method2().method3(); // JavaScript
MyClass->new()->f()->g()->i(); # Perl
Alternately, the most famous yet the least "programming-language" example of this chaining pattern would be something completely non-OO and non-functional ... you guessed it, pipes in Unix. As in, ls | cut -c1-4 | sort -n. Since shell programming is considered a language, I say it's a perfectly valid example.
Well, you can do this in JavaScript and its relatives:
function compose()
{
var funcs = Array.prototype.slice.call(arguments);
return function(x)
{
var i = 0, len = funcs.length;
while(i < len)
{
x = funcs[i].call(null, x);
++i;
}
return x;
}
}
function doubleIt(x) { print('Doubling...'); return x * 2; }
function addTwo(x) { print('Adding 2...'); return x + 2; }
function tripleIt(x) { print('Tripling...'); return x * 3; }
var theAnswer = compose(doubleIt, addTwo, tripleIt)( 6 );
print( 'The answer is: ' + theAnswer );
// Prints:
// Doubling...
// Adding 2...
// Tripling...
// The answer is: 42
As you can see, the functions read left-to-right and neither the object nor the functions need any special implementation. The secret is all in compose.
What you're describing is essentially the Fluent Interface pattern.
Wikipedia has a good example from a number of languages:
http://en.wikipedia.org/wiki/Fluent_interface
And Martin Fowler has his write up here:
http://www.martinfowler.com/bliki/FluentInterface.html
As DVK points out - any OO language where a method can return an instance of the class it belongs to can provide this functionality.
C# extension methods accomplish something very close to your magical language, if a little less concisely:
x.f()
.g()
.h()
.i();
Where the methods are declared thus:
static class Extensions
{
static T f<T>(this T x) { return x; }
static T g<T>(this T x) { return x; }
...
}
Linq uses this very extensively.
Haskell. The following three examples are equivalent:
i(h(g(f(x)))) (Nested function calls)
x & f & g & h & i (Left-to-right chaining as requested)
(i . h . g . f)(x) (Function composition, which is more common in Haskell)
http://www.haskell.org/haskellwiki/Function_composition
http://en.wikipedia.org/wiki/Function_composition_(computer_science)
I am not suggesting you could use Mathematica if you don't do some math usually, but it certainly is flexible enough for supporting Postfix notation. In fact, you may define your own notation, but let's keep with Postfix for simplicity.
You may enter:
Postfix[Sin[x]]
To get
x // Sin
Which translates to Postfix notation. Or if you have a deeper expression:
MapAll[Postfix, Cos[Sin[x]]]
To get:
(Postfix[x]//Sin)//Cos
Where you may see Postfix[x] first, as for Mathematica x is an expression to be evaluated later.
Conversely, you may input:
x // Sin // Cos
To get of course
Cos[Sin[x]]
Or you can use an idiom very frequently used, use Postfix in Postfix form:
Cos[x] // Postfix
To get
x // Cos
HTH!
BTW:
As an answer to Where's with my magical language,? , see this:
(x//Sin
// Cos
// Exp
// Myfunct)
gives
Myfunct[E^Cos[Sin[x]]]
PS: As an excercise to the readers :) ... How to do this for functions that take n vars?
As has been previously mentioned, Haskell supports function composition, as follows:
(i . h . g . f) x, which is equivalent to: i(h(g(f(x))))
This is the standard order of operations for function composition in mathematics. Some people still consider this to be backward, however. Without getting too much into a debate over which approach is better, I would like to point out that you can easily define the flipped composition operator:
infixr 1 >>>, <<<
(<<<) = (.) -- regular function composition
(>>>) = flip (.) -- flipped function composition
(f >>> g >>> h >>> i) x
-- or --
(i <<< h <<< g <<< f) x
This is the notation used by the standard library Control.Category. (Although the actual type signature is generalized and works on other things besides functions). If you're still bothered by the parameter being at the end, you can also use a variant of the function application operator:
infixr 0 $
infixl 0 #
f $ x = f x -- regular function application
(%) = flip ($) -- flipped function application
i $ h $ g $ f $ x
-- or --
x % f % g % h % i
Which is close to the syntax you want. To my knowledge, % is NOT a built-in operator in Haskell, but $ is. I've glossed over the infix bits. If you're curious, thats a technicality that makes the above code parse as:
(((x % f) % g) % h) % i -- intended
and not:
x % (f % (g % (h % i))) -- parse error (which then leads to type error)