小编Kev*_*ith的帖子

期权匹配的Scala类型擦除

object Test {
  def main(args: Array[String]) {
    val list: List[Double] = List(1.0, 2.0, 3.0, 4.0)
    val none = None

    case class Test()

    val test = Test()

    def f(x: Any) = x match {
        case _: Some[Test] => println("_ matched")
        case None => println("None matched")
    }

    f(list)
    f(none)
    f(test)
  }
}
Run Code Online (Sandbox Code Playgroud)

尝试编译上面的代码会导致"擦除"编译时警告.

   $>scalac Test.scala
    Test.scala:11: warning: non-variable type argument Test in type pattern
 Some[Test] is unchecked since it is eliminated by erasure
            case _: Some[Test] => println("_ matched")
                    ^
    one warning …
Run Code Online (Sandbox Code Playgroud)

scala

5
推荐指数
2
解决办法
3288
查看次数

安全地获得阵列的尾巴

我打电话tailArray,但看到了一个警告.

scala> val arr = Array(1,2)
arr: Array[Int] = Array(1, 2)

scala> arr tail
warning: there were 1 feature warning(s); re-run with -feature for details
res3: Array[Int] = Array(2)
Run Code Online (Sandbox Code Playgroud)

Scaladocs for Array显示了一个UnsupportedOperationException [will be thrown] if the mutable indexed sequence is empty.

是否存在安全,不会抛出异常,获取数组尾部的方法?

scala

5
推荐指数
2
解决办法
4600
查看次数

在Monad上实现`sequence`

在另一个练习中实现Monad.sequence()斯卡拉函数式编程,我的回答来自官方不同/知到是正确的答案:

def序列[A](lma:List [F [A]]):F [List [A]]

官方:

def sequence[A](lma: List[F[A]]): F[List[A]] =
  lma.foldRight(unit(List[A]()))((ma, mla) => map2(ma, mla)(_ :: _))
Run Code Online (Sandbox Code Playgroud)

矿:

def sequence[A](lma: List[F[A]]): F[List[A]] = F(lma.flatten)

F的例子是Option:

scala> val x: List[Option[Int]] = List( Some(1), None)
x: List[Option[Int]] = List(Some(1), None)

scala> Some(x.flatten)
res1: Some[List[Int]] = Some(List(1))
Run Code Online (Sandbox Code Playgroud)

我的回答(或其精神)在这里合法吗?

我得到以下编译时异常,但我确定它是否与我对类型构造函数缺乏理解有关.

Monad.scala:15:错误:未找到:值F
F(lma.flatten)

monads scala

5
推荐指数
1
解决办法
1067
查看次数

转发类示例

阅读Effective Java,我从Item 16: Favor composition over inheritance.

在下面InstrumentedSet,这本书显示我们可以跟踪元素被插入的次数(通过InstrumentedSet.addCount变量)。

要做到这一点,我们可以简单地附加到这个类对象的addCount,然后调用ForwardingSet.add(),它调用实际Set类的 实际实现add()

// Reusable forwarding class 
public class ForwardingSet<E> implements Set<E> {     
  private final Set<E> s;     
  public ForwardingSet(Set<E> s) { this.s = s; }     
  public void clear()               { s.clear();            }    
  public boolean contains(Object o) { return s.contains(o); }
...
}

// Wrapper class - uses composition in place of inheritance   
public class InstrumentedSet<E> extends ForwardingSet<E> { …
Run Code Online (Sandbox Code Playgroud)

java effective-java

5
推荐指数
1
解决办法
4505
查看次数

Scala命名为参数

Named ArgumentsScala中深入研究这个例子:

scala> class Parent {
     | def foo(bar: Int = 1, baz: Int = 2): Int = bar + baz
     | }
defined class Parent

scala> class Child extends Parent {
     |    override def foo(baz: Int = 3, bar: Int = 4): Int = super.foo(baz, bar)
     | }
defined class Child

scala> val p = new Parent
p: Parent = Parent@6100756c

scala> p.foo()
res1: Int = 3

scala> val x = new Child
x: Child …
Run Code Online (Sandbox Code Playgroud)

scala

5
推荐指数
1
解决办法
706
查看次数

ui-router的$ urlRouterProvider.otherwise与HTML5模式

请考虑ui-router的wiki中的以下略微修改的代码.

var myApp = angular.module('myApp',['ui.router']);

myApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
    // for any unmatched url
    $urlRouterProvider.otherwise("/state1");

    $locationProvider.html5Mode(true);

    // now set up the states
    $stateProvider
        .state('state1', {
            url: '/state1',
            templateUrl: "partials/state1.html"
        })
        .state('state1.list', {
            url: "/list",
            templateUrl: "partials/state1.list.html",
            controller: function($scope) {
                $scope.items = ["A", "List", "of", "Items"];
            }
        })
        .state('state2', {
            url: "/state2",
            templateUrl: "partials/state2.list.html",
            controller: function($scope) {
                $scope.things = ["a", "set", "of", "things"];
            }
        })
});
Run Code Online (Sandbox Code Playgroud)

运行python 3的SimpleHttpServer,我404 error在尝试访问时得到:http://localhost:8000/state1234324324.

为什么没有$urlRouterProvider.otherwise("/state1");重定向所有未知路由/state1,根据这个问题,已经定义state …

html5 angularjs angular-ui-router

5
推荐指数
1
解决办法
1万
查看次数

总和或产品类型?

给定以下代数数据类型

scala> sealed trait Person
defined trait Person

scala> case class Boy(name: String, age: Int, x: String) extends Person
defined class Boy

scala> case class Girl(name: String, age: Int, y: Boolean) extends Person
defined class Girl
Run Code Online (Sandbox Code Playgroud)

注意 - 我知道它不是递归类型 - 不涉及递归。

那么,这是 aSum还是Product Type?为什么?

scala algebraic-data-types

5
推荐指数
1
解决办法
2105
查看次数

约束左右类型的签名

给出以下AST SuccessFailure:

sealed trait Success
case object FooGood extends Success
case object BarGood extends Success

sealed trait Failure
case object FooBad extends Failure
case object BarBad extends Failure
Run Code Online (Sandbox Code Playgroud)

方法签名:

def go[A <: Failure, B <: Success](x: Int): Either[A, B] = ???
Run Code Online (Sandbox Code Playgroud)

但是,我想约束LeftRight类型特定于FooBar.

但是下面的代码编译(违背我的意愿):

scala> go[FooBad.type, BarGood.type](5)
scala.NotImplementedError: an implementation is missing
Run Code Online (Sandbox Code Playgroud)

如何在编译时实现此约束?

scala

5
推荐指数
1
解决办法
94
查看次数

在编译时添加两个相同大小的列表

在Idris中,我可以通过以下方式添加两个相同大小的向量:

module MatrixMath

import Data.Vect

addHelper : (Num n) => Vect k n -> Vect k n -> Vect k n
addHelper = zipWith (+)
Run Code Online (Sandbox Code Playgroud)

在REPL上编译后:

*MatrixMath> :l MatrixMath.idr 
Type checking ./MatrixMath.idr
Run Code Online (Sandbox Code Playgroud)

然后我可以用两个大小为3的向量来调用它:

*MatrixMath> addHelper [1,2,3] [4,5,6]
[5, 7, 9] : Vect 3 Integer
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试调用addHelper两个不同大小的向量时,它将无法编译:

*MatrixMath> addHelper [1,2,3] [1]
(input):1:20:When checking argument xs to constructor Data.Vect.:::
        Type mismatch between
                Vect 0 a (Type of [])
        and
                Vect 2 n (Expected type)

        Specifically:
                Type mismatch between
                        0
                and
                        2 …
Run Code Online (Sandbox Code Playgroud)

scala dependent-type idris

5
推荐指数
2
解决办法
351
查看次数

从Idris到Scala的通用加法器?

使用Idris进行类型驱动开发提供了以下通用加法器方法:

AdderType : (numArgs : Nat) -> Type
AdderType Z     = Int
AdderType (S k) = (next : Int) -> AdderType k

adder : (n : Nat) -> (acc : Int) -> AdderType n
adder Z acc     = acc
adder (S k) acc = \x => (adder k (x+acc))
Run Code Online (Sandbox Code Playgroud)

例:

-- expects 3 Int's to add, with a starting value of 0
*Work> :t (adder 3 0) 
adder 3 0 : Int -> Int -> Int -> Int

-- …
Run Code Online (Sandbox Code Playgroud)

scala shapeless idris

5
推荐指数
1
解决办法
314
查看次数