How can I make this function more elegant - function

I have the function:
wrap :: Text -> [Text] -> Text
wrap x = intercalate "" . map ((<> x) . (x <>))
The purpose of which is to wrap each element of a list with a given string and join them all together.
The brackets around the first argument to map annoy me, and so does the use of "". So I wonder is there a more elegant (or generic, I guess) way to express this function?

(Copied from my comment so the question can be marked as answered.)
You could use foldMap f instead of intercalate "" . map f. Note that intercalate "" is equivalent to Data.Text.concat.

Just to put my hat in the ring... Since the pattern is
xexxexxex
(where the es are placeholders for elements of the original list), another way you can build this output is by putting two xs between each element, and wrapping the bookends manually. So:
wrap x es = x <> intercalate (x <> x) es <> x
One small but nice feature of this rewrite is that for input lists of length n, this will incur only n+2 calls to (<>) rather than 3n-1 as in theindigamer's answer.

Related

Updating an OM cursor that went through a function

When calling om/build, one can send an fn option, which according to the documentation:
`fn - a function to apply to x before invoking f.`
My question is, when applying om/transact! or om/update! to the cursor (x) that was manipulated by the fn, how does the original cursor get affected?
(om/build comp1 (f cursor)) has the same effect as (om/build comp1 cursor {:fn f})
So the answer is that it really depends what f does. As long as (f x) (or its content) is still a cursor, you can om/transact! or om/update! on it (or its content).
For example, if x is {:x 1} and f is #(update-in % [:x] inc), f will apply on the value of the cursor; the underlying atom will not change. When you om/transact! or om/update! on (f x) it'll operate on the atom inside cursor x. On the next render, you'll once again get (f x) based on the updated x.
On the other hand, if f makes x not a cursor (e.g. f is om/value), then you won't be able to om/transact! or om/update! on it at all.
Hope that helps.

Printing a table with sage math

The assignment is to construct a two-column table that starts at x= -4 and ends with x= 5 with one unit increments between consecutive x values. It should have column headings ‘x’ and ‘f(x)’. I can't find anything helpful on html.table(), which is what we're supposed to use.
This what I have so far. I just have no idea what to put into the html.table function.
x = var('x')
f(x) = (5 * x^2) - (9 * x) + 4
html.table()
You might want to have a look at sage's reference documentation page on html.table
It contains the following valuable information :
table(x, header=False)
Print a nested list as a HTML table. Strings of html will be parsed for math inside dollar and double-dollar signs. 2D graphics will be displayed in the cells. Expressions will be latexed.
INPUT:
x – a list of lists (i.e., a list of table rows)
header – a row of headers. If True, then the first row of the table is taken to be the header.
There is also an example for sin (instead of f) with x in 0..3 instead of -4..5, that you can probably adapt pretty easily :
html.table([(x,sin(x)) for x in [0..3]], header = ["$x$", "$\sin(x)$"])
#Cimbali has a great answer. For completeness, I'll point out that you should be able to get this information with
html.table?
or, in fact,
table?
since I would say we want to advocate the more general table function, which has a lot of good potential for you.

HTML Layout: mixing [Element] and [Signal Element] in an Elm web apge

I am reading about flow down and it's suppose to let us stack elements vertically on our web site. What are you supposed to do when when parts of your website are signals? I would picture a web site like this:
Introduction
Dynamic Component
More Static Text
The type of flow down: [Element] -> Element so I can't just mix in [signal Element] as I would like. In a previous solution I saw solutions involving lift so here's what I came up with:
import Random
main = column <~ (constant "5") ~ (Random.range 0 100 (every second))
column x y = flow down [asText x, asText y]
Here I just stack the number 5 on top of a randomly changing number. Perhaps it depends depends on the Window size,
import Random
import Window
main = column <~ (constant "5") ~ Window.dimensions
column x y = flow down [asText x, asText y]
Is this considered good practice or are there better ways of doing layout in Elm?
Extracting a non-signal function and lifting it is generally good practice. In this case you could also use Signal.Extra.combine : [Signal a] -> Signal [a] if you like:
main = flow down <~ combine [constant (asText "5"), asText <~ Window.dimensions]
As you can see, there is a lot more lifting going on than in your solution, just to get it into a one-liner. So I don't think it's ideal. But combine can be handy in other (more dynamic) situations.
Full disclosure: I'm the author of the library function that I linked to.
Up to date answer.
Either you use combine, which is now in the Signal-extra library or, for this simple case
column x y =
Signal.map (flow down) <|
Signal.map2 (\a b -> [a, b]) (show x) (show y)

How to prevent maxima to rewrite the output of 2*sqrt(2) to 2^(3/2)?

Maxima input of
2*sqrt(2)
by default returns the output
2^(3/2)
How can I get Maxima to just return 2*sqrt(2) ?
(I use this in the tex() function.)
To the best of my knowledge, there is no way to prevent Maxima from simplifying 2*sqrt(2) to 2^(3/2), with two probably-hard-to-use exceptions:
(1) Turn off simplification entirely. But that disables all simplifications, e.g. 1 + 1 simplifying to 2. But if you want to try it: just enter simp : false;.
(2) Disable the simplification sqrt(2) to 2^(1/2) via :lisp (setf (get '%sqrt 'operators) nil) But then Maxima for the most part doesn't know what to do with sqrt.
I don't recommend either one of these.
You can try something like
simp: false;
tex(2*sqrt(2));
block code...;
simp: true;
That way you don't have to disable the simplification permanently.
You can do this:
(%i1) matchdeclare(n_, integerp,m_, integerp)$
tellsimp(n_*sqrt(m_), n_*sqrt(box(m_)))$
and afterwards:
(%i3) 2*sqrt(2);
(%o3) 2 √2
(%i4) sqrt(3)*9;
(%o4) 9 √3
You'll notice that the number under the square root sign in the output is colored red, because of box(). But if you select the expression in wxMaxima, and then popup "Copy LaTeX", you'll get exactly what you want, e. g.
\[2\,\sqrt{2}\]
Unfortunately if you try tex(2*sqrt(2)) to get the TeX code, you'll get $$2\,\sqrt{\boxed{2}}$$instead.

Deleting entire function definition in Vim

I've been trying Vim for any text editing work for almost a week now. I want to know the fastest way to select a C function definition.
For example, if I have a function like this:
void helloworlds( int num )
{
int n;
for ( n = 0; n < num; ++n ) {
printf( "Hello World!\n" );
}
}
How would I be able to delete the whole definition including the function name?
As is common in Vim, there are a bunch of ways!
Note that the first two solutions depend on an absence of blank lines.
If your cursor is on the line with the function name, try d}. It will delete everything to the next block (i.e. your function body).
Within the function body itself, dap will delete the 'paragraph'.
You can delete a curly brace block with da}. (If you like this syntax, I recommend Tim Pope's fantastic surround.vim, which adds more features with a similar feel).
You could also try using regular expressions to delete until the next far left-indented closing curly brace: d/^}Enter
]] and [[ move to the next/previous first-column curly brace (equivalent to using / and ? with that regex I mentioned above. Combine with the d motion, and you acheive the same effect. In addons like Python-mode, these operators are redefined to mean exactly what you're looking for: move from function to function.
How to delete the whole block, header included
If you're on the header/name, or the line before the block, da} should do the trick.
If you're below a block, you can also make use of the handy 'offset' feature of a Vim search. d?^{?-1 will delete backwards to one line before the first occurrence of a first-column opening curly brace. This command's a bit tricky to type. Maybe you could make a <leader> shortcut out of it.
Plugins
I don't do much C programming in Vim, but there are surely plugins to help with such a thing. Try Vim Scripts or their mirror at GitHub.
To delete an entire function, including its definition, such as:
function tick() {
// ...
}
Move to the line with the function name.
Move the cursor to the opening brace, f{ should do it, or simply $.
Press V%d (Visual line, move to matching pair, delete)
If your functions look like this:
function tick()
{
// ...
}
Move to the line with the function name.
Press J (join the current line with line bellow. This also puts your cursor at the last character on the resulting line, {, just the one we need for the next command.)
Press V%d (Visual line, move to matching pair, delete.)
or
Move to the line with the function name.
Press V[Down]%d (Visual line, move one line down, move to matching pair, delete.)
If you are willing to install plugins vim-textobj-function will give you vif for Visual select Inside Function and vaf for Visual select A Function.
daf will delete the function, both the line with the signature and the function body ({})
The text object defined by this plugin are more specific and they don't rely on the function body being a contiguous block of text or { being placed at the first character on the line.
The drawback is that you depend on an external plugin.
You can use this shortcut to delete not only the function, also the lines between curly braces, i.e the code between if-else statements,while,for loops ,etc.
Press Shitf + v [Will get you in visual Mode] at the curly brace start/end.
Then Press ] + } i.e ] + Shitf ] - If you are in start brace.
Then Press [ + { i.e [ + Shitf [ - If you are in end brace.
Then DEL to delete the lines selected.
The simplest and most direct way way is as follows (works anywhere inside function):
v enter visual mode
{ move to first brace in function (may have to press more than once)
o exchange cursor from top to bottom of selection
} extend selection to bottom of function
d delete selected text
The complete command sequence would be v{o}d. Note that you can do other operations besides delete the same way. For example, to copy the function, use y (yank) instead of d.
Use this simple way
1.Go to the function definition
2.dd - delete function definition
3.d -start delete operation
4.shift+5(%) - delete the lines between { to }
If your function were separated by the blank lines, just type:
dip
which means "delete inner paragraph".
Another way is to go to the line of the start of your function and hit: Vj% (or V%% if your style puts the opening brace on the same line). This puts you into Visual-Line mode and the percent takes you to the matching closing brace. In the second style, the first % takes you to the opening brace on the line that you selected and the second to its matching closing brace.
Also works for parentheses, brackets, C-style multi-line comments and preprocessor directives.
See the manual for more info.
Pre-condition: be somewhere inside the function.
Go to the previous closing curly bracket on the first line using
[]
Then delete down to the next closing curly bracket on the first line using
d][
Most posted methods have a downside or two. Usually, when working withing a class definition of some object oriented language, you might not have an empty line after the function body, because many code formatters put the closing braces of last method and class on consecutive lines. Also, you might have annotations on top of the function. To make matters worse, there might be empty lines within your function body. Additionally you'd prefer a method that works with the cursor anywhere within the function, because having to move it to a specific line or worse, character, takes valuable time. Imagine something like
public class Test {
/* ... */
#Test
public void testStuff() {
// given
doSetup();
// when
doSomething();
// then
assertSomething();
}
}
In this scenario, vap won't do you any good, since it stops at the first empty line within your function. v{o} is out for the same reason. va{V is better but doesn't catch the annotation on top of the method. So what I would do in the most general case is va{o{. va{ selects the whole function body (caveat: if your cursor is within a nested block, for instance an inner if statement, then you'll only get that block), o puts the cursor to the beginning of the selection and { selects the whole paragraph prepending your selection. This means you'll get the function definition, all annotations and doc comments.
the most easy way I found is:
Get to the line where the function starts and do this: ^^vf{% to mark the entire function and then whatever you like.
^^ - start of the line
v - start visual mode
f - jump to the next search character
{ - this is the search character
% - jump to the closing brackets
This is also very logical after you have used it a few times.
non-visual way:
d/^}/e
... delete by searching for } at line beining, including it for deletion.
without /e (not mentioned in above answers), solution is incomplete.
with /e - searching goes to end of match, so closing bracket is included, and command is well for yanking too:
y/^}/e
if you use neovim version :>0.5
the modern way is to use treesitter and build your model, then you can be selected or yanked or deleted...
Tree-sitter is a parser generator tool and an incremental parsing library. It can build a concrete syntax tree for a source file and efficiently update the syntax tree as the source file is edited
I suggested this video on youtube to learn how to use treesitter to build your model : Let's create a Neovim plugin using Treesitter and Lua
I tried all the top answers here, but none of them works except the one by Nick which suggests to press f{ to get to the opening curly brace. Then V%d to delete the whole function.
Note that, the whole function gets yanked, so you can paste it elsewhere. I come across this use-case frequently, especially when moving if blocks inside another.
I use this map. It work for me
"delete function definition
"only support function body surround by {}
nnoremap <LEADER>df {v/{<cr>%d