首页 \ 问答 \ 警卫在“无”设置(Guards on “Nothing” Setting)

警卫在“无”设置(Guards on “Nothing” Setting)

更新:

公平地说,我的例子是我正在面对的一个问题的简化,我尝试过实施该解决方案,但似乎并不奏效。

followConnection :: Connection->Crib->Stecker->Offsets->Maybe Stecker
followConnection w x y z
| steckerAdd ((enigmaEncode (getSndTripleEl w) (SimpleEnigma rotor1 rotor2 rotor3 reflectorB) (calculateOffset z (getFirstTripleEl w))), (getThirdTripleEl w)) y == Nothing = Nothing
| steckerAdd ((enigmaEncode (getSndTripleEl w) (SimpleEnigma rotor1 rotor2 rotor3 reflectorB) (calculateOffset z (getFirstTripleEl w))), (getThirdTripleEl w)) y == Just (y) = y

 steckerAdd ((enigmaEncode (getSndTripleEl w) (SimpleEnigma rotor1 rotor2 rotor3 reflectorB) (calculateOffset z (getFirstTripleEl w))), (getThirdTripleEl w)) y == Just (y) = y

给予

无法与类型[(Char, Char)]' with匹配Maybe Stecker'预期类型:可能Stecker实际类型:Stecker

我有一个函数(myFunction),它返回“Maybe Int”作为输出

我想编码类似于:

myOtherFunction :: Int -> Maybe Int
myOtherFunction x
| myFunction x == Nothing = 1
| myFunction x == 1 = 2
| otherwise = 3

然而,Haskell似乎并不喜欢我比较“Ma​​ybe Int”值与int ...

我也尝试将它“铸造”到一个Int中:

| fromMaybe(myFunction) x == 1 = 2

功能是:

fromMaybe :: Maybe a -> a
fromMaybe (Just x)=x

想法?


UPDATE:

To be fair, my example was a simplification of a problem I'm facing, I've tried implementing the solution, but it doesn't seem to work...

followConnection :: Connection->Crib->Stecker->Offsets->Maybe Stecker
followConnection w x y z
| steckerAdd ((enigmaEncode (getSndTripleEl w) (SimpleEnigma rotor1 rotor2 rotor3 reflectorB) (calculateOffset z (getFirstTripleEl w))), (getThirdTripleEl w)) y == Nothing = Nothing
| steckerAdd ((enigmaEncode (getSndTripleEl w) (SimpleEnigma rotor1 rotor2 rotor3 reflectorB) (calculateOffset z (getFirstTripleEl w))), (getThirdTripleEl w)) y == Just (y) = y

With

 steckerAdd ((enigmaEncode (getSndTripleEl w) (SimpleEnigma rotor1 rotor2 rotor3 reflectorB) (calculateOffset z (getFirstTripleEl w))), (getThirdTripleEl w)) y == Just (y) = y

Giving

Couldn't match type [(Char, Char)]' withMaybe Stecker' Expected type: Maybe Stecker Actual type: Stecker

I have a function (myFunction) which returns "Maybe Int" as an output

I would like to code something similar to:

myOtherFunction :: Int -> Maybe Int
myOtherFunction x
| myFunction x == Nothing = 1
| myFunction x == 1 = 2
| otherwise = 3

However, Haskell doesn't seem to like me comparing a "Maybe Int" value to an int...

I also tried "casting" it to an Int by making it:

| fromMaybe(myFunction) x == 1 = 2

Where the function is:

fromMaybe :: Maybe a -> a
fromMaybe (Just x)=x

Ideas?


原文:https://stackoverflow.com/questions/20461183
更新时间:2023-08-07 22:08

最满意答案

  1. 为每个线程定义一个Logger对象。
  2. 对于来自(1)的Logger,禁用向上传递日志层次结构(将additivity设置为false)
  3. 从(1)向Logger添加一个WriterAppender ,传入一个ByteArrayOutputStream实例。
  4. 加入线程后,获取(3)中定义的OutputStream并相应地处理它

例如:

public static void main(String[] args) throws Exception{
    BasicConfigurator.configure();
    LoggerRunner[] runners = new LoggerRunner[]{new LoggerRunner("t1"), new LoggerRunner("t2")};
    Thread t1 = new Thread(runners[0]);
    Thread t2 = new Thread(runners[1]);
    t1.start();
    t2.start();
    t1.join();
    System.out.println("Joined 1");
    t2.join();
    System.out.println("Joined 2");
    System.out.print(new String(runners[0].getLog()));
    System.out.print(new String(runners[1].getLog()));
}

private static class LoggerRunner implements Runnable{

    private final Logger logger;

    private ByteArrayOutputStream logs = new ByteArrayOutputStream();
    private final String name;
    public LoggerRunner(String name){
        this.name = name;
        logger = Logger.getLogger(name);
        logger.setAdditivity(false);
        logger.addAppender(new WriterAppender(new PatternLayout("%-1r [%t] %-5p %c %x - %m%n"), logs));
    }

    public byte[] getLog(){
        return logs.toByteArray();
    }

    @Override
    public void run() {
        logger.info(name + " started");
        try{
            Thread.sleep(1000);
            logger.info(name + " working");
            Thread.sleep(1000);
        }catch(Exception e){}
        logger.info(name + " finished");
    }
}

  1. Define a Logger object per thread.
  2. For Logger from (1), disable passing of logs up the hierarchy (set additivity to false)
  3. Add a WriterAppender to the Logger from (1), passing in a ByteArrayOutputStream instance.
  4. After joining the threads, get the OutputStream defined in (3) and deal with it accordingly

For example:

public static void main(String[] args) throws Exception{
    BasicConfigurator.configure();
    LoggerRunner[] runners = new LoggerRunner[]{new LoggerRunner("t1"), new LoggerRunner("t2")};
    Thread t1 = new Thread(runners[0]);
    Thread t2 = new Thread(runners[1]);
    t1.start();
    t2.start();
    t1.join();
    System.out.println("Joined 1");
    t2.join();
    System.out.println("Joined 2");
    System.out.print(new String(runners[0].getLog()));
    System.out.print(new String(runners[1].getLog()));
}

private static class LoggerRunner implements Runnable{

    private final Logger logger;

    private ByteArrayOutputStream logs = new ByteArrayOutputStream();
    private final String name;
    public LoggerRunner(String name){
        this.name = name;
        logger = Logger.getLogger(name);
        logger.setAdditivity(false);
        logger.addAppender(new WriterAppender(new PatternLayout("%-1r [%t] %-5p %c %x - %m%n"), logs));
    }

    public byte[] getLog(){
        return logs.toByteArray();
    }

    @Override
    public void run() {
        logger.info(name + " started");
        try{
            Thread.sleep(1000);
            logger.info(name + " working");
            Thread.sleep(1000);
        }catch(Exception e){}
        logger.info(name + " finished");
    }
}

相关问答

更多
  • 喜欢@ alan7678说 - 自定义布局也是我的解决方案。 @Plugin(name = "ExtendedJsonLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true) public class ExtendedJsonLayout extends AbstractJacksonLayout { // Lots of code! } 我创建了一个名为“extended ...
  • 一些修正:你的线程迭代应该是for(int t = 0; ...),假设你的线程数组[0]应该参与全局计数器总和。 我们可以猜测它是一个测试数组,而不是线程。 local_counter应该是volatile的,否则你可能在测试线程和主线程中看不到真正的值。 好吧,现在,你有一个适当的2阶段循环,afaict。 任何其他事情都像一个相位器或一个循环屏障,每个循环都有一个新的倒计时锁存器,只是同一主题的变化:获得大量线程同意让主恢复,并让主恢复一个镜头中的多个线程。 较细的实现可能涉及到一个reentrant ...
  • 您有n个工作线程和一个主线程a ,它将任务委派给工作人员,并且必须等待他们完成这些任务,然后再为他们分配一批新任务。 基本技术是使用屏障(如boost::barrier )来同步工作线程的结尾和a 。 屏障在n+1处初始化。 主线程等待屏障,每个工作线程在其任务结束时执行相同操作。 当最后一个线程在屏障上调用wait时,所有线程都被唤醒,主线程可以继续工作。 您可能希望添加第二个屏障来阻止工作线程,直到为其分配新任务。 工作线程的主体可能看起来像以下伪代码: while (running) { s ...
  • 在Android中, 不鼓励停止主线程。 系统将告诉用户应用程序没有响应。 但是,您可以“通知”主线程后台线程已完成其工作。 一旦主线程知道这一点,它就会做一些事情。 它在Android中很常见,它是AsyncTask的用途。 但是, AsyncTask用于简单的一个线程。 在您的情况下,解决方案之一是组合ExecutorService和AsyncTask 。 在你做的AsyncTask实例的doInBackground方法中,像往常一样使用ExecutorService ,并等待shutdown(); a ...
  • OpenMP与其他线程机制的交互故意被排除在规范之外,因此在很大程度上取决于实现。 GNU OpenMP运行时在TLS中保存一个指向线程池的指针,并将其传播到(嵌套)团队中。 通过pthread_create (或boost::thread或std::thread )启动的std::thread不继承指针,因此产生一个新池。 其他OpenMP运行时也可能就是这种情况。 标准中要求在大多数实现中基本上强制这种行为。 它是关于threadprivate变量的语义,以及它们如何在从同一个线程分叉的不同并行区域中保 ...
  • 因为你实际上不打电话加入。 更换: t.join 有: t.join() 重点在于t.join表达式返回bound method对象,并且添加括号使表达式成为方法调用。 连接线程只对用户线程有用,守护进程线程不会阻塞主线程完成。 Because you actually don't call join. Replace: t.join with: t.join() The point is that t.join expression returns bound method object, and ...
  • 为每个线程定义一个Logger对象。 对于来自(1)的Logger,禁用向上传递日志层次结构(将additivity设置为false) 从(1)向Logger添加一个WriterAppender ,传入一个ByteArrayOutputStream实例。 加入线程后,获取(3)中定义的OutputStream并相应地处理它 例如: public static void main(String[] args) throws Exception{ BasicConfigurator.configure( ...
  • 您可以在MSDN博客上使用此示例中演示的TPL生产者/消费者模式。 或者,您可以将其AutoResetEvent旧学校并使用信号,请参阅AutoResetEvent 。 或者,如果您想在非常低的水平上工作,请将Monitor.Pulse与Monitor.WaitOne一起使用(如此处所示)。 无论哪种方式,您正在寻找同步,您可以在这里阅读。 其他选项,如果你实际上并不关心运行更新的线程,那就是将一个委托作为参数并在那里打印更新,àla: static Task ReadFile(string ...
  • 这可以使用RoutingAppender完成。 FAQ页面有一个很好的示例配置。 This can be done with the RoutingAppender. The FAQ page has a good example config.
  • 程序中存在可见性问题:工作线程可能无法观察到在一个线程中发生的worker_done标志的更改。 为了保证一个动作的结果对第二个动作是可观察的,那么你必须使用某种形式的同步来确保第二个线程看到第一个线程的作用。 要解决此问题,您可以使用Jarod42建议的原子。 如果你执行这个程序来实现它很好,但对于真正的应用程序,你可以从现有的线程池中获益,这将大大简化你的代码。 There is visibility issue in your program: the change of worker_done fl ...

相关文章

更多

最新问答

更多
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)
  • 是否可以嵌套hazelcast IMaps?(Is it possible to nest hazelcast IMaps? And whick side effects can I expect? Is it a good Idea anyway?)
  • UIViewAnimationOptionRepeat在两个动画之间暂停(UIViewAnimationOptionRepeat pausing in between two animations)
  • 在x-kendo-template中使用Razor查询(Using Razor query within x-kendo-template)
  • 在BeautifulSoup中替换文本而不转义(Replace text without escaping in BeautifulSoup)
  • 如何在存根或模拟不存在的方法时配置Rspec以引发错误?(How can I configure Rspec to raise error when stubbing or mocking non-existing methods?)
  • asp用javascript(asp with javascript)
  • “%()s”在sql查询中的含义是什么?(What does “%()s” means in sql query?)
  • 如何为其编辑的内容提供自定义UITableViewCell上下文?(How to give a custom UITableViewCell context of what it is editing?)
  • c ++十进制到二进制,然后使用操作,然后回到十进制(c++ Decimal to binary, then use operation, then back to decimal)
  • 以编程方式创建视频?(Create videos programmatically?)
  • 无法在BeautifulSoup中正确解析数据(Unable to parse data correctly in BeautifulSoup)
  • webform和mvc的区别 知乎
  • 如何使用wadl2java生成REST服务模板,其中POST / PUT方法具有参数?(How do you generate REST service template with wadl2java where POST/PUT methods have parameters?)
  • 我无法理解我的travis构建有什么问题(I am having trouble understanding what is wrong with my travis build)
  • iOS9 Scope Bar出现在Search Bar后面或旁边(iOS9 Scope Bar appears either behind or beside Search Bar)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • 有关调用远程WCF服务的超时问题(Timeout Question about Invoking a Remote WCF Service)