How to fill an xtensor array, with complex data type - xtensor

Paraphrasing here, but this is the problem
xt::pyarray< std::complex<double> > output;
output = 0; // fails to compile
output = double(0); // also fails to compile
output = complex<double>(0); // succeeds
and yet this is fine
std::complex<double> foo;
foo = double(0);
The problem is I'm writing a function which accepts arbitrary xtensor array, eg.
template<typename xtarray_t>
void my_function(xtarray_t &output, const xtarray_t &input) {
output = 0;
}
so in general this
output = complex<double>(0);
would fail. I've seen this, but am not sure if this was implemented, or how to use it, couldn't find the documentation. In general though, I think it should still work with std::complex.
thanks for any help!
compiler output:
xtensor-python/include/xtensor-python/pyarray.hpp:360:20: note: candidate function not viable: no known conversion from 'double' to 'const xt::pyarray<std::__1::complex<double>, xt::layout_type::dynamic>::self_type' (aka 'const pyarray<std::__1::complex<double>, (xt::layout_type)0>') for 1st argument
self_type& operator=(const self_type& rhs);
xtensor-python/include/xtensor-python/pyarray.hpp:363:20: note: candidate function not viable: no known conversion from 'double' to 'xt::pyarray<std::__1::complex<double>, xt::layout_type::dynamic>::self_type' (aka 'pyarray<std::__1::complex<double>, (xt::layout_type)0>') for 1st argument
self_type& operator=(self_type&& e) = default;
xtensor-python/include/xtensor-python/pyarray.hpp:369:20: note: candidate template ignored: could not match 'xexpression<type-parameter-0-0>' against 'double'
self_type& operator=(const xexpression<E>& e);

Answer is to do this
using value_t = typename xtarray_t::value_type;
output = value_t(0);

Related

Why can't clang++ deduce this lambda's return value?

Consider the following function:
#include <utility>
#include <iterator>
#include <algorithm>
template<template<class, class> class Map, typename Key, typename Value , typename F>
auto transform_values(const Map<Key,Value>& map, const F& value_mapper)
{
using mapped_value_type = decltype(value_mapper(std::declval<Value>()));
Map<Key, mapped_value_type> transformed;
std::transform(map.cbegin(), map.cend(), std::inserter(transformed, transformed.begin()),
[&value_mapper](const auto& pair) {
const auto& key = pair.first;
const auto& value = pair.second;
return {key, value_mapper(value)};
}
);
return transformed;
}
g++ 12 accepts this, clang++ 14 does not (GodBolt). clang++ 14 says:
<source>:15:20: error: cannot deduce lambda return type from initializer list
return {key, value_mapper(value)};
^~~~~~~~~~~~~~~~~~~~~~~~~~
Why won't it deduce the lambda's type?
I can't see how the compiler can deduce return type here. The return type of the lambda should be convertible to the type pointed to by the output iterator, but without complete container class it doesn't even know what this type is.
Edit.
For the part what rule makes it fail (i.e. why no valid specialization can be generated), i believe it refers to 9.2.9.6.2 Placeholder type deduction / 2.1.2 rule:
A type T containing a placeholder type, and a corresponding initializer-
clause E, are determined as follows:
For a non-discarded return statement that occurs in a function declared with a return type that contains a placeholder type, T is the declared return type.
...
If the operand is a braced-init-list ([dcl.init.list]), the program is ill-formed.

Kotlin: "Type inference failed"

Does someone know what goes I'm doing wrong here?
// ...
val alphabet = ('a'..'z').toList()
val str = "testing"
val arr = str.split("")
for (char in arr) {
var i = alphabet.indexOf(char) // Throws Error!
// ...
}
The indexOf-method results in
"Error:(10, 26) Kotlin: Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly."
I have tried to "var i: Int = alphabet.indexOf(char)" and "alphabet.indexOf(char) as Int". The same result ...
What's the issue here?
I believe that your problem is that you think that the variable char contains a Char value. If that were the case, then it would make sense for indexOf to be accepting a Char value and then finding the location of that character in a list of characters (List<Char>) on which the method is being called.
But str.split() is returning a List<String>, not a List<Char>, and so char is a String. So you are asking the indexOf method to tell you the location of a String in a list of characters (List<Char>). That doesn't make sense. That's the basis of the problem. Exactly how that translates to the error you're getting from the Kotlin compiler, I'm not sure.
To make it clear, this line produces the same error:
var i = alphabet.indexOf("c") // Throws Error!
but the compiler likes this line just fine:
var i = alphabet.indexOf('c') // No Error!!!

Is g++ 4.5.3 broken when it comes to pointers to lamba functions?

I was trying out lambda functions and making a jump table to execute them, but I found g++ didn't recognize the type of the lambda function such that I could assign them to an array or tuple container.
One such attempt was this:
auto x = [](){};
decltype(x) fn = [](){};
decltype(x) jmpTable[] = { [](){}, [](){} };
On compilation I get these errors:
tst.cpp:53:27: error: conversion from ‘main()::<lambda()>’ to non-scalar type ‘main()::<lambda()>’ requested
tst.cpp:54:39: error: conversion from ‘main()::<lambda()>’ to non-scalar type ‘main()::<lambda()>’ requested
Hmmmm, can't convert from type A to non-scalar type A? What's that mean? o.O
I can use std::function to get this to work, but a problem with that is it doesn't seem to work with tuple:
function<void()> jmpTable[] = [](){}; // works
struct { int i; function<void()>> fn; } myTuple = {1, [](){}}; // works
tuple<int, function<void()>> stdTuple1 = {1, [](){}}; // fails
tuple<int, function<void()>> stdTuple2 = make_tuple(1, [](){}); // works
tst.cpp:43:58: error: converting to ‘std::tuple<int, std::function<void()> >’ from initializer list would use explicit constructor ‘std::tuple<_T1, _T2>::tuple(_U1&&, _U2&&) [with _U1 = int, _U2 = main()::<lambda()>, _T1 = int, _T2 = std::function<void()>]’
Constructor marked explicit? Why?
So my question is if I am doing something invalid or is this version just not quite up to the task?
Hmmmm, can't convert from type A to non-scalar type A? What's that mean? o.O
No, that's not a conversion to the same type. Despite having identical bodies, the different lambdas have different types. Newer versions of GCC make this clearer, and give the error message:
error: conversion from '__lambda1' to non-scalar type '__lambda0' requested
clang does even better:
error: no viable conversion from '<lambda at test.cc:2:18>' to 'decltype(x)' (aka '<lambda at test.cc:1:10>')
I can use std::function to get this to work, but a problem with that is it doesn't seem to work with tuple:
It does (with 4.5.4, at least, I don't have 4.5.3 to test), but your initialisation isn't quite right.
tuple<int, function<void()>> stdTuple1 {1, [](){}}; // lose the = to initialise stdTuple1 directly
I'm not sure about the state of n3043 in 4.5.3, but you should be able to use function pointer conversion. If I'm not misunderstanding your usage intentions, this may work for you;
void (*x)();
decltype(x) fn = [](){};
decltype(x) jmpTable[] = { [](){}, [](){} };

pointer to function syntax and usage

I apologize if this was asked many times.
I'm trying to understand why both of this works fine without any warnings or other visible issues (in Xcode):
int testFunctionAcceptingIntPointer(int * p) {
return *p = *p +5;
}
void test() {
int testY = 7;
typedef int (*MyPointerToFunction)(int*);
// Both this (simply a function name):
MyPointerToFunction functionPointer = testFunctionAcceptingIntPointer;
// And this works (pointer to function):
MyPointerToFunction functionPointer = &testFunctionAcceptingIntPointer;
int y = functionPointer(&testY);
}
The code works fine without warnings both ways because a function designator is converted to a function pointer
MyPointerToFunction functionPointer = testFunctionAcceptingIntPointer;
unless it is the operand of the address operator
MyPointerToFunction functionPointer = &testFunctionAcceptingIntPointer;
(or sizeof and _Alignof).
In the first assignment, you don't use &, so the automatic conversion is done, resulting in a function pointer of appropriate type, in the second, you explicitly take the address, resulting in a function pointer of the appropriate type.

Structure of a block declaration

When declaring a block what's the rationale behind using this syntax (i.e. surrounding brackets and caret on the left)?
(^myBlock)
For example:
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
};
C BLOCKS: Syntax and Usage
Variables pointing to blocks take on the exact same syntax as variables pointing to functions, except * is substituted for ^. For example, this is a function pointer to a function taking an int and returning a float:
float (*myfuncptr)(int);
and this is a block pointer to a block taking an int and returning a float:
float (^myblockptr)(int);
As with function pointers, you'll likely want to typedef those types, as it can get relatively hairy otherwise. For example, a pointer to a block returning a block taking a block would be something like void (^(^myblockptr)(void (^)()))();, which is nigh impossible to read. A simple typedef later, and it's much simpler:
typedef void (^Block)();
Block (^myblockptr)(Block);
Declaring blocks themselves is where we get into the unknown, as it doesn't really look like C, although they resemble function declarations. Let's start with the basics:
myvar1 = ^ returntype (type arg1, type arg2, and so on) {
block contents;
like in a function;
return returnvalue;
};
This defines a block literal (from after = to and including }), explicitly mentions its return type, an argument list, the block body, a return statement, and assigns this literal to the variable myvar1.
A literal is a value that can be built at compile-time. An integer literal (The 3 in int a = 3;) and a string literal (The "foobar" in const char *b = "foobar";) are other examples of literals. The fact that a block declaration is a literal is important later when we get into memory management.
Finding a return statement in a block like this is vexing to some. Does it return from the enclosing function, you may ask? No, it returns a value that can be used by the caller of the block. See 'Calling blocks'. Note: If the block has multiple return statements, they must return the same type.
Finally, some parts of a block declaration are optional. These are:
The argument list. If the block takes no arguments, the argument list can be skipped entirely.
Examples:
myblock1 = ^ int (void) { return 3; }; // may be written as:
myblock2 = ^ int { return 3; }
The return type. If the block has no return statement, void is assumed. If the block has a return statement, the return type is inferred from it. This means you can almost always just skip the return type from the declaration, except in cases where it might be ambiguous.
Examples:
myblock3 = ^ void { printf("Hello.\n"); }; // may be written as:
myblock4 = ^ { printf("Hello.\n"); };
// Both succeed ONLY if myblock5 and myblock6 are of type int(^)(void)
myblock5 = ^ int { return 3; }; // can be written as:
myblock6 = ^ { return 3; };
source: http://thirdcog.eu/pwcblocks/
I think the rationale is that it looks like a function pointer:
void (*foo)(int);
Which should be familiar to any C programmer.