end parameter in echo for Nim? - nim-lang

Python has end parameter in print()
print("You" , end = '#')
print("Need2LearnAlot")
Will output --> You#Need2LearnAlot
Does Nim's echo has this kind of parameter?

You can create your own echo procedure, to do so.
proc print(args: varargs[string, `$`], `end`: string = "\n") =
for arg in args:
stdout.write(arg)
stdout.write(`end`)
print 1, 2, 3, `end` = "\n===\n"
Note that end in Nim is a special identifier, so you must escape it like that.
More about varargs: https://nim-by-example.github.io/varargs/

Related

Remove first and last character Groovy

I have a variable that looks like this :
[KEY-1]
I would like to remove the brackets. The brackets are always at the beginning and at the end. I want only the output
KEY-1
How can I make this happen in groovy thanks for the help.
You can use the "-" operator for this
def myVar = '[KEY-1]'
myVar = myVar - '[' - ']'
assert myVar == 'KEY-1'
If your variable may contain another [ or ], you can use indexes for this purpose, as you mentioned you want to remove the beginning / end of the variable:
def myVar = '[KEY-1]'
myVar = myVar[1..myVar.size()-2]
assert myVar == 'KEY-1'
Another way:
def var = '[foobar]'
def clean = var.toList().init().tail().join()
println clean
prints foobar. init gives you all characters except the last and tail gives you all characters except the first.

How to debug print a variable (name) and its value in Nim?

During quick and dirty debugging, I often use expressions like:
echo "variable1: ", variable1, " variable2: ", variable2
How can I leverage Nim's macro system to avoid repeating the variable name?
You can use a varargs macro that iterates over the arguments, and generates an AST which prints both the node's string literal as well as its value. Something like this:
import macros
macro debug*(n: varargs[typed]): untyped =
result = newNimNode(nnkStmtList, n)
for i in 0..n.len-1:
if n[i].kind == nnkStrLit:
# pure string literals are written directly
result.add(newCall("write", newIdentNode("stdout"), n[i]))
else:
# other expressions are written in <expression>: <value> syntax
result.add(newCall("write", newIdentNode("stdout"), toStrLit(n[i])))
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(": ")))
result.add(newCall("write", newIdentNode("stdout"), n[i]))
if i != n.len-1:
# separate by ", "
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(", ")))
else:
# add newline
result.add(newCall("writeLine", newIdentNode("stdout"), newStrLitNode("")))
Example usage:
let x = 2
let y = 3
debug("hello", x, y, x*y)
Output:
hello, x: 1, y: 2, x * y: 6

Apply backspace within a string

I have a string which includes backspace. Displaying it to the commandline will 'apply' the backspaces such that each backspace and the non-backspace character which immediately precedes it cannot be seen:
>> tempStr = ['aaab', char(8)]
tempStr =
aaa
Yet the deletion operation operation only happens when displaying the string. It still has the backspace character, and the 'b', inside it:
>> length(tempStr)
ans =
5
I'm looking for a minimal (ideally some sort of string processing built in) function which applies the backspace operation:
>>f(tempStr)
ans =
'aaa'
It may also help to know that I have an enumerations class over the alphabet 'a' to 'z' plus ' ' and backspace (to store my own personal indexing of the letters, images associated with each etc.). It'd be real spiffy to have this backspace removal operation be a method of the superclass that acts on a vector of its objects.
You can do it with a simple function using a while loop:
function s = printb(s)
while true
% Find backspaces
I = strfind(s, char(8));
% Break condition
if isempty(I), break; end
% Remove elements
if I(1)==1
s = s(2:end);
else
s(I(1)-1:I(1)) = [];
end
end
and the test gives:
s = [char(8) 'hahaha' char(8) char(8) '!'];
numel(s) % returns 10
z = printb(s) % returns 'haha!'
numel(z) % returns 5
This is not really "minimal", but as far as my knowlegde goes I don't think this is feasible with regular expressions in Matlab.
Best,
Your problem can be solved very elegantly using regular expressions:
function newStr = applyBackspaces(tempStr)
newStr = tempStr;
while (sum(newStr==char(8))>0) % while there is at least one char(8) in newStr do:
tmp = newStr; % work on previous result
if (tmp(1) == char(8)) % if first character is char(8)
newStr = tmp(2:end); % then suppress first character
else % else delete all characters just before a char(8)
newStr = regexprep(tmp,[ '.' char(8)],''); % as well as char(8) itself.
end
end
end
In essence, what my function does is delete the character just before the backspace until there are no more backspaces in your input string tempStr.
To test if it works, we check the output and the length of the string:
>> tempStr = ['abc', char(8), 'def', char(8), char(8), 'ghi']
tempStr =
abdghi
>> length(tempStr)
ans =
12
>> applyBackspaces(tempStr)
ans =
abdghi
>> length(applyBackspaces(tempStr))
ans =
6
Hence, tempStr and applyBackspaces(tempStr) show the same string, but applyBackspaces(tempStr) is the same length as the number of characters displayed.

Does MATLAB have a strip function for strings?

Is there a simple function f such that
f(' hello, world! ' ) == 'hello, world!'
I can strip out the spaces (or any character for that matter) using regexes, but this seems like applying a hammer to the problem. I'd just like to know if there is something simple which I've missed.
No need to use a hammer, simply use strtrim.
From the documentation:
S = strtrim(str) returns a copy of string str with all leading and
trailing white-space characters removed. A white-space character is
one for which the isspace function returns logical 1 (true).
To remove the spaces on the side of the string, use the strtrim command.
Since Matlab version 2016b, you can use the built-in strip() function.
For those who do not have the newer matlab version, here is my self-defined function, which also does not have the limitation of exact one char when strCharacter is passed in as strip()
function result = trim(s,varargin)
% Merge multiple spaces to single space in the middle
% remove trailing/leading spaces
% trim(s [, how [,chars]])
% s: a string
% how: a num 1=left only;
% 2=right only;
% 3=left and right;
% 4 (default)=left and right and merge middle
% chars: if not given (default), space
% if given, remove consecutive character instead
%
if nargin == 1
how = 4;
chars = ' ';
elseif nargin == 2
how = varargin{1};
chars = ' ';
elseif nargin == 3
how = varargin{1};
chars = varargin{2};
end % end if nargin
if strcmp(chars,' '), chars='\s'; end
if how==1
expression = sprintf('^(%s)+',chars);
elseif how==2
expression = sprintf('(%s)+$',chars);
elseif how==3
expression = sprintf('^(%s)+|(%s)+$',chars,chars);
elseif how==4
expression = sprintf('(?<=[(%s)])(%s)*|^(%s)+|(%s)+$',chars,chars,chars,chars);
end % end if how
result = regexprep(s, expression, '');
end

FoxPro functions which determine if a variable is a character string or a numeric string

I'm looking for a Visual FoxPro function which is similar to the PHP function is_numeric().
I have found this, but I could not use VARTYPE or TYPE because the variable is always a character string which contains digits only.
I found ISDIGIT() function, but the manual says that it only checks the first character.
Determines whether the leftmost character of the specified character
expression is a digit (0 through 9).
ISDIGIT(cExpression)
Parameters
cExpression
Specifies the character expression that ISDIGIT( ) tests. Any
characters after the first character in cExpression are ignored.
I would create my own function using the regular expression object VBScript.RegExp
FUNCTION isNumeric( tcValue )
LOCAL oRE
oRE = CreateObject("VBScript.RegExp")
oRE.Pattern = '^[0-9]+$'
RETURN oRE.test( tcValue )
ENDFUNC
? isNumeric( '123' )
But, is there any function provided by FoxPro for this purpose?
Am I just overlooking?
Also same for ISALHPA() which determines whether the leftmost character in a character expression is alphabetic. I want to check if the variable contain only alphabets.
You can create your own function like this.
FUNCTION IsAllDigits
LPARAMETERS tcSearched, tcOptionalSearch
* tcSearched = the string of characters to test.
* tcOptionalSearch = optional, additional characters to allow.
LOCAL lcSearch
m.lcSearch = "01234567989" + IIF(VARTYPE(m.tcOptionalSearch) = "C", m.tcOptionalSearch, "")
LOCAL lcRemaining
m.lcRemaining = CHRTRAN(m.tcSearched, m.lcSearch, "")
RETURN ( LEN(m.lcRemaining) = 0 )
ENDFUNC
FUNCTION ISNUMERIC
LPARAMETERS cVal
LOCAL llNumeric, lnLen, lcChr, lnDecs, lnVal
llNumeric = VARTYPE(cVal) = "N" && Donkey has sent a numeric value
lnDecs = 0
DO CASE
CASE llNumeric
CASE VARTYPE(cVal)<>"C" && Not a character
OTHERWISE
cVal = ALLTRIM(cVal) && Trim spaces
lnLen = LEN(cVal) && How many characters
llNumeric = .T. && Assume
i = 0
DO WHILE llNumeric AND i<lnLen
i = i+1
lcChr = SUBSTR(cVal,i,1) && Get next char
lnVal = VAL(lcChr)
DO CASE
CASE lcChr = "0" && Allowed
CASE lnVal>0 && 1 - 9 OK
CASE INLIST(lcChr, "-", "+") && Allowed but ONLY at the start
llNumeric = i = 1
CASE lcChr = "." && Decimal point but ONLY one
lnDecs = lnDecs+1
llNumeric = lnDecs = 1
OTHERWISE
llNumeric = .F.
ENDCASE
ENDDO
ENDCASE
RETURN llNumeric
ENDFUNC
This could work for ISDIGIT() or ISALPHA().
Function IsAllDigits(myValue)
lReturn = .t.
FOR i = 1 TO LEN(myvalue)
IF !ISDIGIT( SUBSTR(myValue, i, 1) )
lReturn = .f.
EXIT
ENDIF
ENDFOR
RETURN lReturn
ENDFUNC
How about a one liner?
Function IsNumeric
Lparameters pString
Return m.pString == Chrtran(m.pString, Chrtran(m.pString, "0123456789", ""), "")
EndFunc
You can any other valid characters to "0123456789" like "." or ","
There is more simple to test if a string is numeric or not :
If String="123" => val('String')>0
If String="AB123" => val('String')=0
That's all...
Using only Visual Fox Pro, you can do something like this:
FUNCTION is_numeric(var_name)
error_trigger=.f. &&** first initialization
&&** evaluate("any_char") will generate an error so I'm using TRY-CATCH-ENDTRY
TRY
EVALUATE(var_name)
CATCH &&** evaluate() generates an error then the string is character
WAIT WINDOW "character"
error_trigger=.t. &&** there was an error returned by evaluate()
EXIT && stop and jump after ENDTRY
ENDTRY
IF error_trigger=.f. &&** there was no error returned by evaluate() then the string was numeric
WAIT WINDOW "numeric"
ENDIF
ENDFUNC
Then call to the function:
is_numeric("333") will show: numeric
is_numeric("aaa") will show: character
is_numeric("333a333") will show: character
I hope it will help you

Resources