What are the implementation strategies for multiple dispatch: class-based, or method-based organization, or either?

Regarding classes and methods, Practical Foundation of Programming Languages by Harper says:

Dynamic dispatch is often described in terms of a particular implementation strategy, which we will call the class-based organization. In this organization, each object is repre- sented by a vector of methods specialized to the class of that object. We may equivalently use a method-based organization in which each method branches on the class of an ob- ject to determine its behavior. Regardless of the organization used, the fundamental idea is that (a) objects are classified and (b) methods dispatch on the class of an object. The class-based and method-based organizations are interchangeable and, in fact, related by a natural duality between sum and product types. We explain this symmetry by focusing first on the behavior of each method on each object, which is given by a dispatch matrix. From this, we derive both a class-based and a method-based organization in such a way that their equivalence is obvious.

More generally, we may dispatch on the class of multiple arguments simultaneously. We concentrate on single dispatch for the sake of simplicity.

Does “we may dispatch on the class of multiple arguments simultaneously” mean “we may dispatch on the method of multiple arguments simultaneously”

For multiple dispatch, what is its implementation strategy? Class-based organization, or method-based organization, or either? (My guess is that class-based organization doesn’t work for multiple dispatch, but only for single dispatch.)


How does one dispatch a helpless opponent?

There is no coup de grace mechanic in D&D 5e like there is in previous editions. So how is a helpless opponent dispatched quickly, mechanically? Is it just a matter of giving the opponent advantage?

It seems like one should be able to deal with someone who is under the effects of a sleep spell, for example, more quickly than just what a to-hit bonus enables.

In what sense if any does java have multiple dispatch?

I’m trying to get my head around the difference between message passing (with which we are all familiar as by far the most common form of object orientation today) vs generic functions as implemented in CLOS (Common Lisp Object System).

In what sense is it possible to say java has a kind of multiple-dispatch system due to method overloading?

To sketch my understanding, in message passing you might do:

tell obja move objb tell objb move obja 

but where the function is first class and not in any object, you might do:

move obja objb 

The part I do think I understand is that with generics there is no dilemma on where to place a function, whereas in message passing you may have to arbitrarily choose which class to put a function on, then just remember which one you put it on. With message passing, if you want to be able to call the behaviour from either, you have to duplicate the code (yes I know there are ways round that, but that’s not the point).

I’m not sure I’m really getting the rest of how generics are different yet.

Dynamic dispatch from a string (Python)

Lets assume I have a string for a class name (or part of a class name), and I have implementation somewhere. All I want, is to be able to get an instance of a class with the name in the variable.

For example,

dynamic_class_name = "Circle"  # not a constant, comes from somewhere corresponding_class = some_magic(dynamic_class_name) corresponding_instance = corresponding_class() 

I can think of several approaches from using __import__() function, module attribute lookups, adding register to classes, other ways of using namespaces, making auto-registering via metaclassing, all the way to using some heavy component architecture and interfaces…

The question is, what would be the simplest but elegant (understandable, intuitive, regular, not hackish) way to replace ugly code like?

if dynamic_class_name == "Circle":   inst = Circle() elif dynamic_class_name == "Square":   inst = Square() ... 

The bonus would be to have minimal impact on IDE’s (like PyCharm) ability to infer types and instances.

Also a plus is that there is no need to have a special list with the classes in one place, so new classes can be drop in.

What is the rationale behind the way modern elevator dispatch systems are implemented?

There have been many elevator upgrade projects with the aim of saving energy and time for the managers and occupants of buildings. I suspect this has to do with the increase in height and volume of people moving in and out of buildings, and one of the trends I have noticed is the system put in place for people to select the floor they want to go to before entering the elevator (so no up or down buttons any more) and being allocated a specific elevator number to enter.

Theoretically the system would be able to calculate the most efficient way to dispatch the elevators if it knows all the floors that people want to exit the elevator. Practically I suspect this depends on the degree which the path of the elevator (i.e. which floors it opens at) can be disrupted with additional requests as it traverses the floors.

I am curious as to whether there have been studies of elevator dispatch algorithms combined with human behaviour to optimize such systems, as I see the factors at play include:

  • The distance between the floor selection control and the elevator door
  • The number of floors in the building
  • The number of elevators in the building
  • The distribution of the occupants in the building that have a need to go to other floors (other than the shared floors like Ground and car park)
  • The amount of disruption allowed to the path of the elevator

So to me this seems like a very complex problem to which a single solution seems to have been proposed that will apparently cater for all these different types of scenarios.

How does the system take into account that this is not the usual behaviour for people used to pressing the call button and selection the floor once they are inside the lift? Are there specific design strategies that makes it more ‘user-friendly’?

Additionally, is there also a higher cost for people who change their mind or get off at the wrong floor and have to try and get back to the correct floor?

But I guess most importantly, as with most designs, people also adjust their behaviour when they are exposed to a new system, so that they end up not necessarily using it the way it is intended.

UPDATE: I tried to do a little bit more research, and apparently I should be looking at Destination Dispatch Systems. There are some companies that explain the systems in more details available:

  • http://www.facilitiesnet.com/elevators/article/Destination-Dispatch-Machineroomless-Systems-Are-Current-Wave-of-Elevator-Technology–13595?source=previous
  • https://www.thyssenkruppelevator.com/elevator-products/elevator-destination-dispatch

How to wait ‘return’ until ‘dispatch’ finish

[React JS]How to wait ‘return’ until ‘dispatch’ finish in action creator? I don’t know how handle this ;(

i made some code. this is a part of action creator. But it return before dispatch finish. i want to dispatch finish before ‘return’. help me please

export const Hello = param=> dispatch => {   return postApi('/hello', param)     .then(async res => {       await dispatch(goHello(res));        return true; }) 

Uncaught Error: Call to a member function dispatch() on null View\Element\AbstractBlock.php on line 652

help needed i am creating a factory in block and get data from model it give result in block but when i return this factory and use this block function in phtml file it give error ” Fatal error: Uncaught Error: Call to a member function dispatch() on null in C:\wamp64\www\hum\vendor\magento\framework\View\Element\AbstractBlock.php on line 652 ” enter image description here

Dispatch different parameters to different classes with single interface

I have a set of classes that have similar funcionality but very different interfaces. I created two interface classes with polymorphic methods so I can operate over then. When creating calling the methods, I have to pass a set of parameters, in this case a JSON file, that is also different for each class. Is there a way to create a generic interface without having to do ifs to select which parameter to pass to each class?

import library_A import library_B  class ApproachA():      def __init__(self, params):         self.params = params         self.entity = library_A.Model(self.params)      def run(self, data):         return self.entity(data)   class ApproachB():      def __init__(self, params):         self.params = params.transpose()         self.entity = library_B.Model(self.params)      def run(self, data):         real_data = data.transpose()         return self.entity(data)   if __name__ == "__main__":      params = {                "model_a": {"param_1":10, "param_2":22},                "model_b": {"thing":"strudel", "param_cc": 102, "talk":False}               }      entity_list = []     # here lies the problem     for key, param in params.items():         if key == "model_a":             entity_list.append(Approach_A(param))         elif key == "model_b":             entity_list.append(Approach_B(param)) 

I definitely want to avoid these ifs sequences and couplings, as things similar to these tests have to be done in several places in the code. I also would like to avoid an abstract base class. I´m trying to keep things as functional as possible, without heavy OO concepts.

ReactJs – Redux – Dispatch não altera o conteúdo das variáveis


import store from './store' import Home from './home';  ReactDOM.render(   <Provider store={store}>     <Home />   </Provider>, document.getElementById('root')); 


import React from 'react'; import {connect} from 'react-redux'; import query from './utils/query';  class Home extends React.component {  componentWillMount() {   this.props.dispatch({type:'MOUNT_TOKEN'}); } componentDidMount() {     this.queryHeaderComponents(); } componentWillUnmount(){   this.props.dispatch({type:'UMOUNT_TOKEN'}); } queryHeaderComponents = () => {   let header = {     headers: {       'Content-Type': 'application/json',       'Authorization': `$  {this.props.tokenType} $  {this.props.token}`     }   }   query(`$  {this.props.url}/api/user`, 'GET', header, '', (result) => {     this.setState({       name:result.name,     });   } } render(){   return <div>{this.state.nome}</div> } const mapStateToProps = state => {   return ({     token: state.token,     tokenType: state.tokenType,     url: state.url   }); } export default connect(mapStateToProps)(Home); 


import { createStore } from 'redux'; import query from '../utils/query';  const initialState = {   token:null,   tokenType:null, }  const umountToken = state => {   state.token = null;   state.tokenType = null;   return state; }  const mountToken = state => {   state.token = localStorage.getItem('access_token');   state.tokenType = localStorage.getItem('token_type');   return state; }  const reducer = (state =  initialState, action) => {   switch (action.type) {     case 'UMOUNT_TOKEN':      return umountToken(state);     case 'MOUNT_TOKEN':       return mountToken(state);     default:       return state;   } }  const store =  createStore(reducer);  export default store; 

Utilizando do método dispatch eu procuro atualizar as variáveis dentro do Redux e então utilizar delas no meu código, porém não consigo atualiza-las. Comecei a utilizar Redux a pouco devido a necessidades que o Redux cobre enfim, no meu ciclo: primeiro o React faz o mapStateToProps, em seguida o componentWillMount entra em ação executando o dispatch(e de fato a função é executada porém os valores não são atribuídos) e por fim o componentDidMount executa sua ação fazendo uma query simples em busca do nome do usuário, contudo header recebe valores nulos e com isso o nome do usuário não é recuperado. Constatei através do debugger que a função dispatch é executada porém pode ser que minha falta de experiência em Redux e porque não considerar falta de experiência em JS/React que tenha feito com que a variável state(store/index.js) não receba os valores corretos, enfim agradeço a ajuda.