Format specifier for a complex matrix - formatting

I already read about the format specifier for complex numbers in here fortran format specifier for complex number
However I was not able to modify it to my wishes. I have double complex matrix of known dimension and I want it to be written like this:
{1.000E+00, 0.000E+00} {2.123E+00, 6.545E+20} {5.456E+24, 5.562E+12} ....
{1.000E+00, 0.000E+00} {2.123E+00, 6.545E+20} {5.456E+24, 5.562E+12}
{1.000E+00, 0.000E+00} {2.123E+00, 6.545E+20} {5.456E+24, 5.562E+12}
...
So the first part in the curly brackets should be the real part and the second part the imaginary part. The matrix elements should be in curly brackets each and placed next to each other according to the position in the matrix.
So far I could just print out one element correctly or all matrix elements under each other with the following format: ("{",ES10.3, ",", 1X, ES10.3 ,"}")
EDIT:
program test
implicit none
double complex :: zz
double complex, dimension(3,4) :: aa
character (len=32) :: fmtString
zz = cmplx(1.d0, -2.d0)
fmtString = '("{",ES10.3, ",", 1X ES10.3,"}")'
write(0,fmt = fmtString) zz !works
write(0,fmt = fmtString)aa !not formatted propperly
end program test
results in something like this, since aa is not initialized:
{ 1.000E+00, -2.000E+00} <- zz works
{ 9.881-324, 9.387-323} <- aa doesn't since it is not displayed as a 3x4 matrix
{ 6.953-310, 0.000E+00}
{ 0.000E+00, 0.000E+00}
{ 1.812-314, 6.953-310}
{ 0.000E+00, 1.019-312}
{ 0.000E+00, 0.000E+00}
{ 4.496-322, 0.000E+00}
{ 0.000E+00, 2.631-312}
{ 0.000E+00, 2.631-312}
{ 0.000E+00, 1.210-316}
{ 1.210-316, 1.210-316}
{ 1.210-316, 3.953-323}
So how do I proceed?

program test
implicit none
double complex :: zz
double complex, dimension(3,4) :: aa
character (50) :: fmtString
integer :: i
zz = cmplx(1.d0, -2.d0)
aa = zz ! aa needs to be initialized too
fmtString = '(9999("{",ES10.3,",",1X,ES10.3,"}",:,1X))'
write(*,fmt = fmtString) zz
do i=1,size(aa,1)
write(*,fmt = fmtString) aa(i,:)
enddo
end program test

Related

Match inside match - ocaml raises syntax error

Does anyone know why this function raises the syntax error? I haven't provided my written side functions, since they are probably not that relevant here, since it's revolving around proper syntax.
I tried deleting the brackets that raised the error (which I think.. should be there?), only to then raise another syntax error one line lower, at the begining of the row with the line "|".
type 'a grid = 'a Array.t Array.t
type problem = { initial_grid : int option grid }
type available = { loc : int * int; possible : int list }
type state = { problem : problem; current_grid : int option grid; available = available list }
let branch_state (state : state) : (state * state) option =
if prazni_kvadratki state.current_grid = [] then
None
else
let lst = prazni_kvadratki state.current_grid in
let loc = List.hd lst in
let st1_grid = copy_grid state.current_grid in
let st2_grid = copy_grid state.current_grid in
match razpolozljive state.current_grid loc with
| x :: xs -> (vstavi_vrednost st1_grid loc (Some x);
let st1 = {problem = state.problem; current_grid = st1_grid} in
match xs with
| [y] -> (vstavi_vrednost st2_grid loc (Some y);
let st2 = {
problem = state.problem;
current_grid = st2_grid
}) (* this is where it shows me a syntax error*)
| y :: ys -> let st2 = {
problem = state.problem;
current_grid = copy_grid state.current_grid;
available = {loc = loc; possible = xs}
})
Some (st1, st2)
On around the 5th last line or so you have let with no matching in. The let expression always must have an in.
The basic rule for nested match is that you should use parentheses or begin/end around the inner one:
match x with
| [] -> 0
| [_] ->
begin
match y with
| [] -> 1
| _ -> 2
end
| _ -> 3
Otherwise the final cases of the outer match look like they belong to the inner one. I don't think this is your problem here because you have no outer cases after the inner match.
Syntax issues
You have a few syntax issues.
type state = { problem : problem; current_grid : int option grid; available = available list }
You likely meant to have:
type state = { problem : problem; current_grid : int option grid; available : available list }
However, given how you construct values later in your program where you provide a value for the available field in one case but not in the other, you may want a variant type that allows your state type to be constructed with or without this value, with distinct behavior when not constructed with this value. This might look like:
type state =
| With_available of { problem : problem;
current_grid : int option grid;
available : available list }
| Without_available of { problem : problem;
current_grid : int option grid }
The other syntax issue is missing an in to go with a let which brings us to:
Scoping issues
There are clearly some miunderstandings here for you in regards to how scope works with let bindings in OCaml.
Aside from a definition at the topmost level of a program, all let bindings are local bindings. That is, they apply to a single expression that trails an in keyword.
Consider this toplevel session.
# let x = 5;;
val x : int = 5
# let y =
let x = 42 in
x + 3;;
val y : int = 45
# x;;
- : int = 5
#
Here the x bound with let x = 42 in x + 3 is only in scope for the duration of the expression x + 3. Once we're done with that expression, that binding for x is gone. In the outer scope, x is still bound to 5.
In both cases in your match you bind names st1 and st2, which would have to be local bindings, but then you try to use them in an outer scope, where they don't exist.
If you want st1 and st2, you'd need to bind them in a similar way to a and b in the below simple example.
# let (a, b) = match [1; 2; 3] with
| [x] -> (x, x)
| x :: y :: _ -> (x, y)
| _ -> (1, 1)
in
a + b;;
- : int = 3
#
Pattern-matching
Please also note that the pattern-matching you're shown is not exhaustive. It does not handle an empty list. If you consider it impossible that an empty list will be a result, you still have to either handle it anyway or use a different data structure than a list which can by definition be empty.
You've shown pattern-matching of the basic pattern:
match some_list with
| x :: xs ->
match xs with
| [y] -> ...
| y :: xs -> ...
We can actually match against the two possibilities you've show in one level of match.
match some_list with
| x :: [y] -> ...
| x :: y :: ys -> ...
If you still need to address y :: ys as xs in the second case, we can readily bind that name with the as keyword.
match some_list with
| x :: [y] -> ...
| x :: (y :: ys as xs) -> ...

How to make uppercase records in purescript?

I have an API that forces me to return a JSON in the form of
{ Field1: "something"
, Field2: 12 }
However, I have failed to model this in Purescript so far.
I understand that the purescript grammar sees the upper case field names and thinks it is the type of a field without a field name. So I it is not straight forward to just encode a function like
test :: Number -> { Field1 :: String, Field2 :: Number }
Without resorting to using external javascript functions to change the object into something else, is it at all possible to construct a record with upper case field names in purescript? And if so, how?
Absolutely! PureScript allows any field names, not just "valid identifier" ones. You just have to double-quote them if they're weird:
x :: { "Field1" :: String, "Field2" :: String, "🍕" :: String }
x = { "Field1": "foo", "Field2": "bar", "🍕": "yum" }
y :: String
y = x."🍕"
Basically same deal as in JavaScript.

Converting String using specific encoding to get just one character

I'm on this frustrating journey trying to get a specific character from a Swift string. I have an Objective-C function, something like
- ( NSString * ) doIt: ( char ) c
that I want to call from Swift.
This c is eventually passed to a C function in the back that does the weightlifting here but this function gets tripped over when c is or A0.
Now I have two questions (apologies SO).
I am trying to use different encodings, especially the ASCII variants, hoping one would convert (A0) to spcae (20 or dec 32). The verdict seems to be that I need to hardcode this but if there is a failsafe, non-hardcoded way I'd like to hear about it!
I am really struggling with the conversion itself. How do I access a specific character using a specific encoding in Swift?
a) I can use
s.utf8CString[ i ]
but then I am bound to UTF8.
b) I can use something like
let s = "\u{a0}"
let p = UnsafeMutablePointer < CChar >.allocate ( capacity : n )
defer
{
p.deallocate()
}
// Convert to ASCII
NSString ( string : s ).getCString ( p,
maxLength : n,
encoding : CFStringConvertEncodingToNSStringEncoding ( CFStringBuiltInEncodings.ASCII.rawValue ) )
// Hope for 32
let c = p[ i ]
but this seems overkill. The string is converted to NSString to apply the encoding and I need to allocate a pointer, all just to get a single character.
c) Here it seems Swift String's withCString is the man for the job, but I can not even get it to compile. Below is what Xcode's completion gives but even after fiddling with it for a long time I am still stuck.
// How do I use this
// ??
s.withCString ( encodedAs : _UnicodeEncoding.Protocol ) { ( UnsafePointer < FixedWidthInteger & UnsignedInteger > ) -> Result in
// ??
}
TIA
There are two withCString() methods: withCString(_:) calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of UTF-8 code units. Example:
// An emulation of your Objective-C method.
func doit(_ c: CChar) {
print(c, terminator: " ")
}
let s = "a\u{A0}b"
s.withCString { ptr in
var p = ptr
while p.pointee != 0 {
doit(p.pointee)
p += 1
}
}
print()
// Output: 97 -62 -96 98
Here -62 -96 is the signed character representation of the UTF-8 sequence C2 A0 of the NO-BREAK SPACE character U+00A0.
If you just want to iterate over all UTF-8 characters of the string sequentially then you can simply use the .utf8 view. The (unsigned) UInt8 bytes must be converted to the corresponding (signed) CChar:
let s = "a\u{A0}b"
for c in s.utf8 {
doit(CChar(bitPattern: c))
}
print()
I am not aware of a method which transforms U+00A0 to a “normal” space character, so you have to do that manually. With
let s = "a\u{A0}b".replacingOccurrences(of: "\u{A0}", with: " ")
the output of the above program would be 97 32 98.
The withCString(encodedAs:_:) method calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of code units. Example:
let s = "a\u{A0}b€"
s.withCString(encodedAs: UTF16.self) { ptr in
var p = ptr
while p.pointee != 0 {
print(p.pointee, terminator: " ")
p += 1
}
}
print()
// Output: 97 160 98 8364
This method is probably of limited use for your purpose because it can only be used with UTF8, UTF16 and UTF32.
For other encodings you can use the data(using:) method. It produces a Data value which is a sequence of UInt8 (an unsigned type). As above, these must be converted to the corresponding signed character:
let s = "a\u{A0}b"
if let data = s.data(using: .isoLatin1) {
data.forEach {
doit(CChar(bitPattern: $0))
}
}
print()
// Output: 97 -96 98
Of course this may fail if the string is not representable in the given encoding.

How to pass a logical R object to a data block in a Stan file

If a list of data includes a logical variable x, namely, x=TRUE or x=FALSE.
Then how to declare such a variable in a Stan file?
For example, if an R object x is an integer, then
data{
int <lower=0>x;
}
I want to know its logical version. I guess
data{
bool x;
}
and it does not work as following;
SYNTAX ERROR, MESSAGE(S) FROM PARSER:
error in 'foo' at line 16, column 0
-------------------------------------------------
14:
15:
16: bool x;
^
17:
-------------------------------------------------
PARSER EXPECTED: <one of the following:
a variable declaration, beginning with type,
(int, real, vector, row_vector, matrix, unit_vector,
simplex, ordered, positive_ordered,
corr_matrix, cov_matrix,
cholesky_corr, cholesky_cov
or '}' to close variable declarations>
Error in stanc(filename, allow_undefined = TRUE) :
failed to parse Stan model 'foo' due to the above error.
Stan does not have a proper boolean type. Like C and C++, we use integer value 0 to denote false and value 1 to denote true. To implement a boolean type in Stan, declare it as an integer with a lower bound of 0 (false) and upper bound of 1 (true).
int<lower = 0, upper = 1> c;
R distinguishes integer types from logical types, but allows a lot of conversion. For example, if we define b to be the result of comparing 1 with itself, its value is TRUE and its type is logical (logi in R):
> b = (1 == 1)
> b
[1] TRUE
> str(b)
logi TRUE
So if I write this Stan program whose behavior differs on a passed boolean,
data {
int<lower = 0, upper = 1> b;
}
parameters {
real y;
}
model {
if (b)
y ~ normal(0, 1);
else
y ~ normal(10, 10);
}
RStan is happy to coerce the boolean, so it's OK to have
fit <- sampling(model, data = list(b = b))
where the value b is a logi type in R.
I believe logicals are resolved to their integer values of 0L for FALSE and 1L for TRUE, so using int is appropriate.

Perl6 optional function flags

How can I implement functions that take an optional flag in Perl6? For example, say that I want to invoke my function like this:
format 'a b c';
or like this:
format :pretty 'a b c';
How can I do this? Thanks
It's just a named argument, in case of flags a boolean one. This all works out because :pretty is syntactic sugar for the pair :pretty(True) aka pretty => True.
You can either use the boolean value
sub format($arg, Bool :$pretty = False) {
if $pretty { ... }
else { ... }
}
or use its presence for multi-dispatch
multi format($arg) { ... }
multi format($arg, Bool :$pretty!) { ... }
In the first example, we provided a default value (which isn't really necessary as the undefined value boolifies to False, but it's arguably the 'right thing to do' semantically), in the second one we made it a required parameter by adding the !.
Also note that named arguments still have to be separated by commas, ie you'd use it as
format :pretty, 'a b c';
If you really want that odd syntax, you can use an operator and some subsignature magic. The Bool method is optional and the class Pretty can be empty. It's just there to provide something for the MMD-dispatcher to hold onto.
class Pretty { method Bool {True} };
sub prefix:<:pretty>(|c){ Pretty.new, c };
multi sub format((Pretty:D $pretty, |a)){ dd $pretty.Bool, a };
multi sub format(|c){ dd c };
format :pretty 'a b c'; format 'a b c';
# OUTPUT«Bool::True␤\(\("a b c"))␤\("a b c")␤»