带空列表的Scala案例选项

时间:2018-03-24 14:37:45

标签: scala

设置:

import csv
import numpy as np
import lmfit
import matplotlib.pyplot as plt
import sys
from scipy.optimize import minimize

#open file with x and y coordinates.
with open('data_data_011.csv', 'r') as csvfile: 
    plots= csv.reader(csvfile, delimiter=',')

    table = [row for row in plots]
    for row in table:
        x = float(row[0])
        y = float(row[1])

    else:
#open file with radius in it.
        with open('data_test02.csv') as file:   
            data = csv.reader(file, delimiter=',')

            table1 = [row for row in data]
            for row in table1:
                z = float(row[0])

def fun(x):
    for row in table:
        x = float(row[0])
        y = float(row[1])
        for row in table1:
            z = float(row[0])
            x1 = 20
            y1 = 20
            Rz = 3
            x_m = x1+Rz * np.cosh((1/Rz)*(y-y1-(z/2)))
            diff_sq = (x - x_m)**2
            sum_diff_sq =+ diff_sq
            print(x_m, diff_sq)
fun(x)

我希望获得所有具有" AA"的值的总和。在元组中。它的效果非常好:

val l = List(("AA",473.3), ("BB",676.48), ("AA",685.45), ("GG",812.73))

但如果var totAA = l.collect{ case ("AA",v) => v }.sum 是一个空列表,我会收到此错误:

l

所以我尝试了这个:

cmd78.sc:1: constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: Nothing
var totAA = l.collect{ case ("AA",v) => v }.sum
                            ^cmd78.sc:1: ambiguous implicit values:
 both object BigIntIsIntegral in object Numeric of type scala.math.Numeric.BigIntIsIntegral.type
 and object IntIsIntegral in object Numeric of type scala.math.Numeric.IntIsIntegral.type
 match expected type Numeric[B]
var totAA = l.collect{ case ("AA",v) => v }.sum

但是我得到同样的错误,不那么冗长:

var totAA = l.collect{ case List() => 0.0; case ("AA",v) => v }.sum

1 个答案:

答案 0 :(得分:4)

您的代码适用于空列表和非空列表。

这里是非空的:

val l = List(("AA",473.3), ("BB",676.48), ("AA",685.45), ("GG",812.73))
var totAA = l.collect{ case ("AA",v) => v }.sum
println(totAA) // output: 1158.75

空的相同:

val l = List.empty[(String, Double)]
var totAA = l.collect{ case ("AA",v) => v }.sum
println(totAA) // output: 0.0

您确定是否创建了空List[(String, Double)],而不是空List[Nothing]Nothing无法与("AA", v)进行模式匹配,因为它显然不是元组。根据定义,Nothing根本不能与任何内容进行模式匹配,因为没有Nothing类型的值。