Scala理解中的println [英] println in scala for-comprehension

查看:362
本文介绍了Scala理解中的println的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于理解,我不能只发表一份印刷声明:

In a for-comprehension, I can't just put a print statement:

def prod (m: Int) = {
  for (a <- 2 to m/(2*3);
    print (a + "  ");
    b <- (a+1) to m/a;
    c = (a*b) 
    if (c < m)) yield c
}

但是我可以通过一个虚拟任务轻松地绕开它:

but I can circumvent it easily with a dummy assignment:

def prod (m: Int) = {
  for (a <- 2 to m/(2*3);
    dummy = print (a + "  ");
    b <- (a+1) to m/a;
    c = (a*b) 
    if (c < m)) yield c
}

有副作用,并且仅在开发中的代码中使用(到目前为止),有没有更好的临时解决方案?

Being a side effect, and only used (so far) in code under development, is there a better ad hoc solution?

除了有副作用之外,为什么我不应该使用它还有一个严重的问题吗?

Is there a serious problem why I shouldn't use it, beside being a side effect?

从与雷克斯·克尔(Rex Kerr)的讨论开始,有必要显示原始代码,这有点复杂,但似乎与问题无关(2x .filter,最后调用一个方法),但是当我尝试将Rex模式应用到它时,我失败了,所以我将其发布在这里:

From the discussion with Rex Kerr, the necessity has risen to show the original code, which is a bit more complicated, but did not seem to be relevant for the question (2x .filter, calling a method in the end), but when I tried to apply Rex' pattern to it I failed, so I post it here:

  def prod (p: Array[Boolean], max: Int) = {
    for (a <- (2 to max/(2*3)).
        filter (p);
      dummy = print (a + "  ");
      b <- (((a+1) to max/a).
         filter (p));
      if (a*b <= max)) 
        yield (em (a, b, max)) }

这是我的尝试-(b * a).filter错误,因为结果是一个int,而不是可过滤的int集合:

Here is my attempt -- (b * a).filter is wrong, because the result is an int, not a filterable collection of ints:

  // wrong: 
  def prod (p: Array[Boolean], max: Int) = {
    (2 to max/(2*3)).filter (p).flatMap { a =>
      print (a + " ")
      ((a+1) to max/a).filter (p). map { b => 
        (b * a).filter (_ <= max).map (em (a, b, max))
      }
    }
  }

第二部分属于注释,但如果在此处写,则无法阅读-也许我最后将其删除.请原谅.

Part II belongs to the comments, but can't be read, if written there - maybe I delete it in the end. Please excuse.

好-这是Rex在代码布局中的最后答案:

Ok - here is Rex last answer in code layout:

  def prod (p: Array[Boolean], max: Int) = {
    (2 to max/(2*3)).filter (p).flatMap { a =>
      print (a + " ")
      ((a+1) to max/a).filter (b => p (b) 
        && b * a < max).map { b => (m (a, b, max))
      }
    }
  }

推荐答案

这是您需要编写的方式:

This is how you need to write it:

scala> def prod(m: Int) = {
     |   for {
     |     a <- 2 to m / (2 * 3)
     |     _ = print(a + " ")
     |     b <- (a + 1) to (m / a)
     |     c = a * b
     |     if c < m
     |   } yield c
     | }
prod: (m: Int)scala.collection.immutable.IndexedSeq[Int]

scala> prod(20)
2 3 res159: scala.collection.immutable.IndexedSeq[Int] = Vector(6, 8, 10, 12, 14
, 16, 18, 12, 15, 18)

这篇关于Scala理解中的println的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆