gpt4 book ai didi

scala - 在scala中的模式匹配中检索类型参数

转载 作者:行者123 更新时间:2023-12-04 11:36:31 25 4
gpt4 key购买 nike

我已经发现可以 bind the type parameter在模式匹配中

为什么在那种情况下不起作用?

trait T

case class S[A](a: A) extends T

def pr(t1: T, t2: T) = (t1, t2) match {
case (S(a): S[ta], S(b): S[tb]) => println(a); println(b)
}
^
error: '=>' expected but ':' found.

有关信息,这有效:

def pr(t1: T, t2: T) = (t1, t2) match {
case (s1: S[a], s2: S[b]) => println(s1.a); println(s2.a)
}

还有这个:

def pr(t1: T, t2: T) = (t1, t2) match {
case (S(a), S(b)) => println(a); println(b)
}

我需要恢复类型以定义其他无法推断其类型的函数,因为在 eta-expansion 的上下文中.

更新

正如评论中提到的,我需要的类型只是为了正确的类型检查,而不是其他任何东西。

例如:

trait T
case class S[A](a: A, w: A => Int) extends T
def makeTwo(t1: T, t2: T) = (t1, t2) match {
case (S(a1, w1), S(a2, w2)) =>
val wNew = { (a, b) => w1(a) + w2(b) }
S((a, b), wNew)
}

error: missing parameter type
val wNew = { (a, b) => w1(a) + w2(b) }
^

最佳答案

引用Scala语法规则:

varid ::= lower idrest

idrest ::= {letter | digit} [‘_’ op]

op ::= opchar {opchar}

opchar ::= “all other characters in \u0020-007F and Unicode
categories Sm, So except parentheses ([]) and periods”

// 'a' and 'a_-' is valid, 'a(' is not.

Typed Pattern 匹配规则说:

Pattern1 ::= varid ‘:’ TypePat
| ‘_’ ‘:’ TypePat

所以

def pr(list: Any) = list match {

case a :String => // works
case a_- :String => // works a_- is valid instance of 'varid'
case a() :String => // does not work.
case a(b) :List[Int] // does not work either!
}

因此:

case S(a): S[ta]  is not valid syntax for pattern match.

但是以下是有效的

case (s1 :S[a], s2: S[b])

根据Tuple Pattern匹配规则:

SimplePattern ::= ‘(’ [Patterns] ‘)’
Patterns ::= Pattern {‘,’ Patterns}

除了您列出的两个可能选项外,您还可以使用:

 case tup: (S[_], S[_]) => 

以下似乎有效:

trait T

case class S[A](a: A, w: A => Int) extends T

def makeTwo(t1: T, t2: T) = (t1, t2) match {
case (S(a1, w1), S(a2, w2)) =>
val wNew = { tup:(Any, Any) => w1(tup._1) + w2(tup._2) }
S((a1, a2), wNew)
}

def someString (s: String) = { s.length }

val twoS = makeTwo(S("Hello", someString), S("World!", someString))
println(twoS.w(twoS.a)) // gives 11

关于scala - 在scala中的模式匹配中检索类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20329118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com