Coq define a type constructor for injective functions

An injective function from type A to B maps distinct inputs to distinct outputs, but might not cover the entire range.

e.g.

f : ℕ -> ℕ
f = λx. 2*x

I’m trying to figure out how to express such a thing in Coq.

I think the Coq way of talking about such an object would be some kind of product type where one element is the is the “raw” function A -> B itself and another is a proof that said function is injective.

I don’t know how to express this in the syntax of Coq though … more specifically how to be able to refer to the name of the function in the definition of a type in the same “structure” and what kind of product-like thing is most appropriate.

I’ve tried putting a number of things in the ellpises here, but am not able to capture the function.

Definition injection (A : Prop) (B: Prop) :=
  A -> B / ...

I’m stuck on what to put in the ellipses.

All topic

How to inject constructor which has two times the same interface with Autofac

I want to replace my Unity IoC in my Xamarin 3.2 App with Autofac IoC. Because I haven’t any experience with Autofac and the documentation explained not what I need, I hope anyone can help me.

I don’t know, how I have to configure the constructor injection, if the class has two interface of the same type, but with different implementations. My example shows two repositories and a facade. I want to give both repositories (same type) the facade constructor.

What I have.

public class CustomerRepository : IRepository
{
       public CustomerRepository(Context context)
       {
       }
}
public class AgentRepository : IRepository
{
       public AgentRepository(Context context)
       {
       }
}
public class ToDoFacade : IFacade
{
	public ToDoFacade(IRepository agentRepository, IRepository customerRepository)
	{
	}
}

// IoC registration

public class Registry
{
    public Registry()
    {
	var builder = new ContainerBuilder();
	builder.RegisterType<AgentRepository>().As<IRepository>().PreserveExistingDefaults();
	builder.RegisterType<CustomerRepository>().Named<IRepository>("Customer");

// How can I continoue here?
	builder.RegisterType<ToDoFacade>().As<IFacade>().UsingConstructor(...);
    }
}

Do you have an idea for me, how I can solve it? Links to resources are also welcome.

Best Tino

All topic

How do I implement lambda/compareTo in my constructor classes?

I’m trying to have a better understanding of using lambda in Java and have no real idea what I’m doing with it. I have a Heap object and am asked to construct an empty heap using the compareTo method of its data type as the comparator:

public class Heap> implements HeapAPI
{
    /**
     * A complete tree stored in an array list representing this
     * binary heap
     */
    private ArrayList tree;
    /**
     * A comparator lambda function that compares two elements of this
     * heap when rebuilding it; cmp.compare(x,y) gives 1. negative when x 
less than y
     * 2. positive when x greater than y 3. 0 when x equal y
     */
    private Comparator cmp;

    /**
     * Constructs an empty heap using the compareTo method of its data type 
as the
     * comparator
     */
    public Heap()
    {
        tree = new ArrayList();
    }

    /**
     * A parameterized constructor that uses an externally defined comparator
     * @param fn - a trichotomous integer value comparator function
     */
    public Heap(Comparator fn)
    {


    }
}

Just to clarify, I’m referencing the two constructors. I am not necessarily asking for the answer to this but more so an example similar to this situation. Anything is appreciated, thanks.

All topic

What is better explicit conversion through constructor or implicit function in this case?

I am creating my own class for String using C++ solely for learning purposes.

And I stuck upon the place where I should make a decision. Let me explain the matter.

I have two options of my class. I will post below only relevant pieces of the code because I do not want to distract you from my problem at hand. If in order to help me out you need more info I will gladly provide it.

Option 1

class String {
    size_t _length;
    char* _stringHead;
public:
    String(const std::string&);
    String(const char*);
    String(const char);
};
String operator+(String, const String);

const bool operator==(const String, const String);
const bool operator!=(const String, const String);
const bool operator<(const String, const String);
const bool operator<=(const String, const String);
const bool operator>(const String, const String);
const bool operator>=(const String, const String);

Option 2

class String {
    size_t _length;
    char* _stringHead;
public:
    //irrelevant part of code in Option 2
    String(const std::string&);
    String(const char*);
    String(const char);
    //irrelevant part of code in Option 2
};
String operator+(String, const String&);

const bool operator==(const String&, const String&);
const bool operator!=(const String&, const String&);
const bool operator<(const String&, const String&);
const bool operator<=(const String&, const String&);
const bool operator>(const String&, const String&);
const bool operator>=(const String&, const String&);

//for std::string
String operator+(String, const std::string&);

const bool operator==(const String&, const std::string&);
const bool operator!=(const String&, const std::string&);
const bool operator<(const String&, const std::string&);
const bool operator<=(const String&, const std::string&);
const bool operator>(const String&, const std::string&);
const bool operator>=(const String&, const std::string&);

String operator+(const std::string&, String);

const bool operator==(const std::string&, const String&);
const bool operator!=(const std::string&, const String&);
const bool operator<(const std::string&, const String&);
const bool operator<=(const std::string&, const String&);
const bool operator>(const std::string&, const String&);
const bool operator>=(const std::string&, const String&);
//for std::string

//the same goes for char* and char
...
//the same goes for char* and char

So, as you can see from the Option 1 and Option 2 specs the decision here is about whether to use explicit type conversion which is done with the help of constructors or to type each utility separately for each type with which I want my String type to work.

As far as I can see right now the benefit of using the first approach is that it is easier to implement and maintain. While the second approach may produce better performance results.

I would like to get constructive arguments which approach is better and in what scenarios and which approach hence would you use. I think that the biggest part I am interested here is whether or not the performance benefit of the second approach is reasonable.

All topic

Extends constructor

I have a class that extends MagentoCustomerBlockAccountDashboardInfo and I want to extends its constructor to get customer session, but how do I extends constructor ?

PhpStorm is highlighting my constructor I don’t know why (the same constructor than a “regular” constructor of one of my custom block)

All topic

PowerMock Enum Private Constructor Mocking

Unable to private enum constructor.

Please find below MySingleton enum with private constructor, in this constructor I am creating creating service which makes remote call. In my test i want to mock this constructor so that in junit execution my test will not connect remote server.

Using powermock to mock enum constructor. I am able to inject enum instance using Whitebox class of powermock. Also able to get mock service when mock instance is called.

Using to mock invocation of private constructor using whenNew(MySingleton.class).withAnyArguments().thenReturn(instance) but private constructor of enum is not getting mock and test is trying to connect to remote service.

How to mock invocation of private constructore in enum ?

public enum MySingleton {
Instance;

private MyService service

private MySingleton () {
  // service initialization. service connect to remote server
  service = new MyService();
  System.out.println("Constructor Invoke");
}

public Myservice getService() {

return service;
}

}

public class DriverClass {

public void initService() 
 {
  MySingleton.Instance.getService();

 }

}

@RunWith(PowerMockRunner.class)
@PrepareForTest(MySingleton.class)
public class DriverClassTest {

@Mock private Myservice service;
private MySingleton instance;

@before
public void setup() {
instance = mock(MySingleton.class);
Whitebox(MySingleton.class,"Instance",instance);
whenNew(MySingleton.class).withAnyArguments().thenReturn(instance);
}

@test
public void testInitSerice()
 {
when(instance.getService()).thenReturn(service);

new DriverClass().initService();

}

}

All topic

Error: StartCoinCrowdsale contract constructor expected 5 arguments, received 6

This is my contract code.

    contract StartCoinCrowdsale is TimedCrowdsale, MintedCrowdsale, CappedCrowdsale, FinalizableCrowdsale   { //100000000000 

    uint256 public constant TOTAL_SHARE = 100;
    uint256 public constant CROWDSALE_SHARE = 80;
    uint256 public constant FOUNDATION_SHARE = 20;
    function StartCoinCrowdsale
        (
            uint256 _openingTime,
            uint256 _closingTime,
            uint256 _rate,
            address _wallet,
            uint256 _cap,
            MintableToken _token
        )
        public
        Crowdsale(_rate, _wallet, _token) 
        TimedCrowdsale(_openingTime, _closingTime) 
        CappedCrowdsale(_cap)
        FinalizableCrowdsale() {
    }

    function finalization() internal {
        uint256 totalSupply = token.totalSupply();
        uint256 finalSupply = TOTAL_SHARE.mul(totalSupply).div(CROWDSALE_SHARE);//100*8000/80=10000

        // emit tokens for the foundation
        MintableToken(token).mint(wallet, FOUNDATION_SHARE.mul(finalSupply).div(TOTAL_SHARE));//20*10000/100=2000
        super.finalization();
    }
}

This is my deployment code

    module.exports = function (deployer, network, accounts) {
    const openingTime = web3.eth.getBlock('latest').timestamp + 2; // two secs in the future
    const closingTime = openingTime + 120; // 3 minutes
    // const closingTime = openingTime + 86400 * 20; // 20 days
    const rate = new web3.BigNumber(1000);
    const wallet = accounts[1];
    const cap = new web3.BigNumber(8000000000000000000); //8 ether
    return deployer
        .then(() => {
            return deployer.deploy(StartCoin);
        })
        .then(() => {
            console.log(openingTime, closingTime, cap, wallet, rate, StartCoin.address);
            return deployer.deploy(
                StartCoinCrowdsale,
                openingTime,
                closingTime,
                rate,
                wallet,
                cap,
                StartCoin.address
            );
        })
        .then(() => { // giving the crowdsale ownership over the token
            return StartCoinCrowdsale.deployed().then(crowdsale => {
                crowdsale.token().then(tokenAddress => {
                    const startCoinInstance = StartCoin.at(tokenAddress);
                    startCoinInstance.transferOwnership(crowdsale.address).then(output => {})
                })
            }).catch(err => {
                console.log(err);
            })
        });
};

This is my error.

    Running migration: 2_deploy_contracts.js
  Running step...
  Deploying StartCoin...
  ... 0xf719c61552cc15ddf5f951a95a7261d3b8aa6cbb4a6109940bd54dc9b004e6a5
  StartCoin: 0xa8a6b3b9fc3db2831bafc68c4ee60b32e5e49c87
1525510753 1525510873 BigNumber { s: 1, e: 18, c: [ 80000 ] } '0x93a0fd6e1af85eab7045244e972704b498836bcb' BigNumber { s: 1, e: 3, c: [ 1000 ] } '0xa8a6b3b9fc3db2831bafc68c4ee60b32e5e49c87'
  Deploying StartCoinCrowdsale...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: StartCoinCrowdsale contract constructor expected 5 arguments, received 6
    at /usr/lib/node_modules/truffle/build/webpack:/~/truffle-contract/contract.js:390:1
    at new Promise ()
    at /usr/lib/node_modules/truffle/build/webpack:/~/truffle-contract/contract.js:374:1
    at 
    at process._tickCallback (internal/process/next_tick.js:182:7)

Any help would be appreciated.

All topic

The Factory Pattern Equivalent of the Constructor Pattern

I am using the constructor pattern for creating my objects like below;

// Traditional constructor function
const Car = function( color, speed, oil )
{
    this.color = color;
    this.config = { speed: speed, oil: oil };
    // ...
}

Car.prototype.internal = function()
{
    console.log( "internal" );
    // ...
}

Car.prototype.gas = function()
{
    this.internal();
    console.log( this.color );
    // ...
}

Car.prototype.brake = function()
{
    console.log( this.config );
    // ...
}

And I want to change my design to an equivalent of this design but with factory functions. So I wrote the following code;

// Factory Design with Delegation
const carProto = ( function()
{
    const carPrototype = {};
    // Private function
    function internal()
    {
        console.log( "internal" );
        // ...
    }

    // Public function
    carPrototype.gas = function()
    {
        internal();
        console.log( this.color );
        // ...
    }

    carPrototype.brake = function()
    {
        console.log( this.config );
        // ...
    }

    return carPrototype;
} )();

function carFactory( color, speed, oil ) 
{
    return Object.assign( Object.create( carProto ), 
    { 
        color: color,
        config: { speed: speed, oil: oil } 
    } );
}

Finally, I create my objects as follows;

var mazdaF = carFactory( "red", 10, 130 );
var mazdaT = new Car( "yellow", 20, 120 );

I want to know whether this is correct or not. If this is not true, can anybody help me with the best way to implement that?

All topic

Verifying Parameters in Constructor or Service

I was reading on this SO page about when to check parameters when constructing on object. The accepted answer suggests throwing the exception from the constructor, so that an invalid object cannot be constructed.

I agree with that approach, and I can’t see how a Person can be constructed without a name.

However one of the comments suggested:

I also agree that second option is better because it is more reusable
than the first one. First option is violating Object Oriented
Principles. Even factory method is better design than that.

Questions:

  1. Exactly what OOP principles are being violated when you throw an exception in the constructor? Is it guideline that a constructor shouldn’t do work?

  2. The other approach suggested by the OP was a PersonService, however, this is just speculation, but with this approach are you hoping that the client code will call public void addPerson(Person personToAdd) to verify that the person object doesn’t contain a null? What happens if they find a away to circumvent that check? Or before public void addPerson(Person personToAdd) they use that object in another class not written by them that expects a valid Person object?

All topic

Constr is not a constructor on layout.js line 137 error custom module

I have gone through this posts and tried to implement the answers and suggestions

Magento2 getting ‘Constr is not a constructor’ error for custom theme && Error in layout.js, cart not loading && No Way to Clear/delete a Selected Image using Media Browser on category edit page

But I am not able to resolve this issue .

Here is what I have done -> I am trying to reuse module-checkout/view/frontend/web/js/view/billing-address.js file in my custom module, Here is what I have done so far

This is my registration.js file

This is Rahul/Learning/etc/module.xml file



    

This is Rahul/Learning/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/view/billing-address': {
                'Rahul_Learning/js/view/billing-address': true
            }
        }
    }
};

and at location Rahul/Learning/view/frontend/web/js/view I have copy pasted module-checkout/view/frontend/web/js/view/billing-address.js file without any changes but I am getting this error on checkout page

enter image description here

Looking forward for your suggestions not sure what I am doing wrong here.

Thanks

All topic