I need a very special (and small) function in Swift 5.
The function will take an arbitrary string as argument, the only thing known about the argument is that it contains at least one of the characters 'a' or 'b'.
The function is only interested in the characters 'a' and 'b', ignoring the others.
If the last found is an 'a', it returns 'a', if is a 'b' it returns 'b'.
For example, let f be this function.
f("aaa") // returns a.
f("a3242avfvabbba54gg") // returns a.
f("abaagdfb") // returns b.
f("479wfwrvfb8709iho") // returns b.
It is obviously easy to write such a function, but I want to know if there is a particularly clean way in Swift 5 using the last API.
I found the last(where:) method of String, but no sample code to make its usage clear. So I am not sure if that is what I want to use.
You are correct that this function can be implemented with last(where:):
func f(_ s: String) -> Character {
return s.last(where: "ab".contains)!
}
Note that I have used ! to force unwrap because you said there always will be an a or b.
Related
Please explain to a beginner how the function of finding a maximum in the dictionary works.
I know there are more concise solutions, but I want to understand step by step what is going on here.
var someDictionary = ["One": 41, "Two": 17, "Three": 23]
func maxValue() {
let maxValueOfSomeDictionary = someDictionary.max { a, b in a.value < b.value }
print(maxValueOfSomeDictionary!.value)
}
maxValue()
someDictionary is a Dictionary. A Dictionary is a kind of Sequence (see the "Default Implementations" section of Dictionary to know that it's a Sequence). Sequences provide the method max(by:), which:
Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
Swift has trailing-closure syntax, so you can write .max {...} instead of .max(by: { ... }). The two syntaxes are identical, but most developers use trailing-closure syntax when possible.
The parameter is defined as:
areInIncreasingOrder
A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.
The Element of Dictionary as a Sequence is a tuple (key: Key, value: Value), so this is the type that is passed to areInIncreasingOrder.
The closure defines two parameters, a and b, each of type (key: Key, value: Value). It returns whether a.value is less than b.value. Swift allows 1-statement closures to omit the return.
This paragraph is somewhat technical and you may want to skip it. The TL;DR is that max returns the maximum element according to your closure. Provided the closure obeys the rules defined in the docs, the max algorithm will return the maximum element, for a specific definition of "maximum," which is that there is no element in the sequence that is ordered after this one according to areInIncreasingOrder. This pedantic definition especially matters when there are incomparables in the list. Equal elements are (somewhat strangely IMO) defined as "incomparable" in that neither is before the other. This also matters for values like NaN.
This will return a maximum element, or nil if the Sequence is empty. (The docs say "the" maximum element, but in the case of incomparable elements, it is not promised which one will be returned.)
maxValueOfSomeDictionary is of type (key: String, value: Int)?, an optional version of the Element of the Dictionary, since it may be a value or it may be nil.
maxValueOfSomeDictionary! converts an Optional into its wrapped value, or crashes if the Optional is nil. This then prints the .value of that.
To see precisely how max operates, you can read the default implementation in stdlib.
Is it possible to define and use a function like this?
generate_mode_matrix_and_mode_frequency_and_Hw(generate_Hw: true);
function generate_mode_matrix_and_mode_frequency_and_Hw(generate_Hw)
if generate_Hw ## NOTICE: this argument is optional
.....
end
end
What I want is to specify the name of the argument when passing it. In ruby it's called hash.
The point of doing this is that, when using it, the coder know what the true mean without comment. This is
Compare this 2:
generate_mode_matrix_and_mode_frequency_and_Hw(generate_Hw: true)
generate_mode_matrix_and_mode_frequency_and_Hw(true)
Clearly, the first one is more clear.
Notice: generate_Hw is an optional argument. So without specifying it, the function would also work.
You can use something similar to Property\Value pairs:
function Foo(varargin)
for n=1:2:nargin
switch varargin{n}
case 'var1'
var1 = varargin{n+1};
case 'var2'
var2 = varargin{n+1};
end
end
In this example if you use Foo('var1',value) then var1 would get the desired value. If you don't specify the pair 'var1',value in the input, then var1 will not exist in Foo.
How can I create an interface for an array that accepts both numbers and strings?
Since inside the function [1,'1'], ['1','1'],[1,1] are equivalent (they are joined inside as '1.1'), I can't seem to satisfy the compiler. It gets me TS2087: Could not select overload for 'call' expression.
works for fn([1,1]); and fn(['1','1']); but not mixed values.
It's not possible. I suggest to use any[]:
function fn(arr: any[]) {
alert(JSON.stringify(arr));
}
fn([1, 1]);
fn(['1', '1']);
fn(['1', 1]);
I'm trying to write a function that puts the class, length, and value of each of the things in a cell array into a struct, but I keep getting an error with the switch statements
function [ out, common ] = IDcell( cA )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
cl={};
val={};
len={};
for x=1:length(cA)
switch cA(x)
case isnum
cl(x)='double';
case ischar
cl(x)='char';
case islogical
cl(x)='logical';
case iscell
cl(x)= 'cell';
end
val=[val cA{x}];
len=[len size(value(x))];
end
out=struct('value', val, 'class', cl, 'length', len);
end
[out]=IDcell(cA)
SWITCH expression must be a scalar or string constant.
Error in IDcell (line 8)
switch cA(x)
isnum is not a Matlab function. isnumeric may be what you were thinking of, but it isn't what you typed. Which means your code is seeing case isnum and it has no idea what the heck isnum is, so it is telling you whatever it is, if you want to use it there you need to make it something that evaluates to a number (what it means by scalar) or to a piece of text (what it means by string constant).
Further, ischar is a matlab function, but you are not using it the right way. You must use it as ischar(cA(x)) for example, will then evaluate to true if cA(x) is a string or snippet of text, will evaluate to false if cA(x) is anything else.
While it would be lovely if switch worked this way, it doesn't. You can't put a thing in the switch part, and then just list functions that need to be evaluated on that thing in the switch part.
The kind of thing you can do is this:
switch class(x)
case 'double'
fprintf('Double\n');
case 'logical'
fprintf('Logical\n');
end
Here I have used the class function the way it needs to be used, with an argument in it. And I then switch my cases based on the output of that function, class outputs a string.
I wrote a code that finds the root of a function whose name is provided among the arguments, I think I took it from Numerical Recipes. Something like
double precision function rtsafe(x_init, x1, x2, xacc, func, dfunc)
where func and dfunc are two functions' names.
Of course I use rtsafe with different function func and dfunc.
I would like to print the name of the called functions func and dfunc when I am inside rtsafe, because when there is an error in rtsafe I would like to know which function I was using. Something like
write(,)"my func = ", func
(?)
Does anybody know how to do that?
You could add an optional argument in your functions that returns the name of the function:
FUNCTION f(x, fname) RESULT (fx)
IMPLICIT NONE
REAL :: x, fx
CHARACTER(LEN=*), OPTIONAL :: fname
CHARACTER(LEN=*), PARAMETER :: myfname='somename'
IF (present(fname)) fname=myfname
fx = x ! or whatever else
END FUNCTION f
In the first call to your function in rtsafe you get the name of the function for later printing in case of an error.
Did not test this but it should work more or less like this, and it the only way I can think of to do this in Fortran.
Maybe you can work up some manual solution (pass the name of the function, then print it with "OK" ... or something like that), but printing the names of the functions/subroutines (reflecting) is not possible.