我有一个列表,我希望过滤结果.
用户可以为行上的任何属性提供特定限制(例如,我只想查看x == 1的行).如果它们没有指定限制,那么当然不使用谓词.当然,最简单的形式是:
list.filter(_.x == 1)
Run Code Online (Sandbox Code Playgroud)
有许多可能的简单谓词,我正在构建一个新的谓词函数,其代码将用户搜索项(例如Option [Int])转换为谓词函数或Identity(返回true的函数).代码看起来像这样(缩短了,为了清楚起见添加了显式类型):
case class ResultRow(x: Int, y: Int)
object Main extends App {
// Predicate functions for the specific attributes, along with debug output
val xMatches = (r: ResultRow, i: Int) => { Console println "match x"; r.x == i }
val yMatches = (r: ResultRow, i: Int) => { Console println "match y"; r.y == i }
val Identity = (r : ResultRow) => { Console println "identity"; true }
def makePredicate(a: …Run Code Online (Sandbox Code Playgroud) LinkedIn上的人们一直在以有趣的方式使用Play来处理需要由许多不同组件组成的页面:http://engineering.linkedin.com/play/composable-and-streamable-play-apps
他们如何做到的关键组成部分是Play中的"动作"返回完整的响应,因此能够通过更高级别的动作"组合"成另一个响应.
Grails似乎并没有真正从动作中返回任何东西(或者至少没有任何特定的东西),并且当你在一个动作中时,没有一种简单的方法可以调用另一个动作.
那么,Grails可以采用这种构图方式吗?
我正在取一些我在 VS2010 中编写的 MEF 代码,并在 VS2012 中再次编写它。不幸的是,我卡在了这个简单的界面上:
public interface IModulesContainer
{
[ImportMany]
IEnumerable<Lazy<IModule, IModuleMetadata>> Container { get; }
}
Run Code Online (Sandbox Code Playgroud)
VS2012 在这方面有一个编译错误:
Error Using the generic type 'System.Lazy<T>' requires 1 type arguments
Run Code Online (Sandbox Code Playgroud)
我知道有两个 System.Lazy<> 泛型类,一个采用一种参数类型,另一个采用两种(第二个是元数据)。
我不知道如何让 VS2012 识别后一类。(两者都在 System 命名空间下)
VS2010 看到它就好了。我错过了什么?
提前致谢,--埃里克
我想使用组合并使用C++功能为每个可能的重载(noexcept,const,volatile)编写好的转发方法.
我们的想法是使用traits来确定方法是否被声明{noexcept/const/volatile/etc.}并相应地表现.
这是我想要实现的一个例子:
struct User{
UsedObject& obj;
User(UsedObject& obj) : obj(obj) {}
FORWARD_METHOD(obj, get); //here is where the forwarding happens
};
struct UsedObject{
string m{"Hello\n"};
string& get(double d){
cout << "\tUsed :const not called...\n";
return m;
}
const string& get(double d) const{
cout << "\tUsed :const called...\n";
return m;
}
};
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止**:
// forward with noexcept attribute
// I'm not 100% sure about : std::declval<std::add_lvalue_reference<decltype(obj)>::type
template<typename... Args>
constexpr decltype(auto) get(Args && ... args)
noexcept(
noexcept(std::declval<std::add_lvalue_reference<decltype(obj)>::type>().get( std::forward<Args>(args)... ))
and
std::is_nothrow_move_constructible<decltype( std::declval<std::add_lvalue_reference<decltype(obj)>::type>().get( …Run Code Online (Sandbox Code Playgroud) (问题的简化形式。)我正在编写一个涉及一些 Python 组件的 API。这些可能是函数,但为了具体起见,我们假设它们是对象。我希望能够从命令行解析各种组件的选项。
from argparse import ArgumentParser
class Foo(object):
def __init__(self, foo_options):
"""do stuff with options"""
"""..."""
class Bar(object):
def __init__(sef, bar_options):
"""..."""
def foo_parser():
"""(could also be a Foo method)"""
p = ArgumentParser()
p.add_argument('--option1')
#...
return p
def bar_parser(): "..."
Run Code Online (Sandbox Code Playgroud)
但现在我希望能够构建更大的组件:
def larger_component(options):
f1 = Foo(options.foo1)
f2 = Foo(options.foo2)
b = Bar(options.bar)
# ... do stuff with these pieces
Run Code Online (Sandbox Code Playgroud)
美好的。但是如何编写合适的解析器呢?我们可能希望像这样:
def larger_parser(): # probably need to take some prefix/ns arguments
# general options to be overridden by p1, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Jackson 来为我管理类型,但我想使用组合而不是使用继承来创建类型,并拥有一组带有一些注释的工厂方法,这些注释将指示 Jackson 这些是什么类型。具体例子:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
public interface MyInterface {
void doStuff();
// Factories
@JsonCreator
@JsonSubTypes.Type(value = MyInterface.class, name = "impl1")
static MyInterface impl1() {
return new MyInterfaceWithComposition(() -> System.out.println("Impl1"));
}
@JsonCreator
@JsonSubTypes.Type(value = MyInterface.class, name = "impl2")
static MyInterface impl2() {
return new MyInterfaceWithComposition(() -> System.out.println("Impl2"));
}
}
public class MyInterfaceWithComposition implements MyInterface {
private final Runnable task;
public MyInterfaceWithComposition(Runnable task) {
this.task = task;
}
@Override
public void doStuff() {
task.run();
}
} …Run Code Online (Sandbox Code Playgroud) 我完全坚持这是一个优秀的Haskell编程书的练习.
给定以下类型组合的新类型以及Functor和Applicative的实例,编写一个实例Traversable (Compose f g).
newtype Compose f g a =
Compose { getCompose :: f (g a) }
deriving (Eq, Show)
instance (Functor f, Functor g) => Functor (Compose f g) where
fmap f (Compose fga) = Compose $ (fmap . fmap) f fga
instance (Applicative f, Applicative g) => Applicative (Compose f g) where
pure = Compose <$> pure . pure
Compose f <*> Compose x =
Compose $ ((<*>) <$> f) <*> x …Run Code Online (Sandbox Code Playgroud) 是否可以撰写例如:
(defn- multiple-of-three? [n] (zero? (mod n 3))
(defn- multiple-of-five? [n] (zero? (mod n 5))
Run Code Online (Sandbox Code Playgroud)
成:
multiple-of-three-or-five?
Run Code Online (Sandbox Code Playgroud)
所以我可以用它来过滤:
(defn sum-of-multiples [n]
(->> (range 1 n)
(filter multiple-of-three-or-five?)
(reduce +)))
Run Code Online (Sandbox Code Playgroud)
另外我不想像这样定义它:
(defn- multiple-of-three-or-five? [n]
(or (multiple-of-three? n)
(multiple-of-five? n)))
Run Code Online (Sandbox Code Playgroud)
例如,使用Javascript模块Ramda,它将实现为:http://ramdajs.com/docs/#either
const multipleOfThreeOrFive = R.either(multipleOfThree, multipleOfFive)
Run Code Online (Sandbox Code Playgroud) 基于MPJ的这段出色的“ 继承中合成”视频,我一直试图在TypeScript中制定合成。我想组成类,而不是对象或工厂函数。到目前为止,这是我的努力(在lodash的帮助下):
class Barker {
constructor(private state) {}
bark() {
console.log(`Woof, I am ${this.state.name}`);
}
}
class Driver {
constructor(private state) {}
drive() {
this.state.position = this.state.position + this.state.speed;
}
}
class Killer {
constructor(private state) {}
kill() {
console.log(`Burn the ${this.state.prey}`);
}
}
class MurderRobotDog {
constructor(private state) {
return _.assignIn(
{},
new Killer(state),
new Driver(state),
new Barker(state)
);
}
}
const metalhead = new MurderRobotDog({
name: 'Metalhead',
position: 0,
speed: 100, …Run Code Online (Sandbox Code Playgroud) 我在Angular中有一个结构如下的模块:
moduleName
componentA
componentB
Run Code Online (Sandbox Code Playgroud)
现在componentA和componentB它们非常相似,因为它们共享一些属性和方法,例如:
protected available: boolean = true;
Run Code Online (Sandbox Code Playgroud)
因为不想重复自己,所以我创建了一个基类,用于存储所有这些内容:
export abstract class BaseComponent {
protected available: boolean = true;
}
Run Code Online (Sandbox Code Playgroud)
并且两个控制器都从该类继承:
import { BaseComponent } from '../base.component';
export class ComponentA extends BaseComponent implements OnInit {
constructor() {
super();
}
ngOnInit() {
console.log(this.available);
}
}
Run Code Online (Sandbox Code Playgroud)
这样很好。但是,当我研究这种灵魂时,很多人都在说:
不要使用继承,在这种情况下请使用合成。
好的,但是我该如何使用合成呢?与当前解决方案相比,收益真的那么大吗?
非常感谢您的宝贵时间。
composition ×10
inheritance ×2
javascript ×2
typescript ×2
angular ×1
angular6 ×1
argparse ×1
c#-4.0 ×1
c++ ×1
class ×1
clojure ×1
ecmascript-7 ×1
grails ×1
haskell ×1
httpresponse ×1
jackson ×1
java ×1
json ×1
mef ×1
python ×1
scala ×1
scalaz ×1
templates ×1
types ×1