2016-03-04 178 views
0

我试图从IntList获得第一个和最后一个元素。以下是我现在想:斯卡拉匹配列表

def find(lista: List[Integer]) : (Int,Int) = { 
    case (x) => (x,x) 
    case (x1,x2) => (x2,x2) 
    case hd :: _ :: tail => find(tail) 
} 

我正在排队find(tail)一个警告:

type mismatching found List[Any], required List[Integer] 
+0

什么是您收到确切的错误?它是一个'MatchError'吗?请相应地更新您的问题。 – Eric

+1

另外,除非这是一个学术练习,为什么不尝试'(lista.head,lista.last)'? – Eric

+0

我知道这是可能的,我只是想不这样做大声笑 – miechooy

回答

2

这是因为你已经错过了match声明在你的代码,即它应该是,

def find(lista: List[Int]): (Int, Int) = lista match { 
    //cases go here 
} 

你也有一些问题提取(唐元组“T比赛List) 因此前几个case语句应该是,

{ 
    case h :: Nil => (h, h) 
    case h1 :: h2 :: Nil => (h1, h2) 
    ... 
} 

你什么实际上已经完成在错过match是由scala转换成FunctionPartialFunction。输入类型为Any的原因是前两个case语句与元组匹配,而不是List,因此它将类型扩展为Any

最后的代码是,

def find(lista: List[Int]) : (Int,Int) = lista match { 
    case h :: Nil => (h, h) 
    case h1 :: h2 :: Nil => (h1, h2) 
    case hd :: _ :: tail => find(tail) 
} 
+0

:) find(List(1,2,3,4))==(3,4); find(List(1,2,3))==(3,3); find(List(1,2))==(1,2) – nikiforo

+0

@nikiforo你是对的 - 我实际上并没有仔细阅读刚才翻译过的函数的实际点。 – yw3410

2

在这里你对阵一个元组:

case (x1,x2) => (x2,x2) 

如果你要玩与递归和模式匹配,你可以做像这样做:

object HeadTail{ 
    def find(lista: List[Int]) : (Int,Int) = { 
    @tailrec 
    def getLast(l: List[Int]): Int = l match { 
     case h :: Nil => h 
     case h :: tail => getLast(tail) 
    } 

    lista match { 
     case Nil => throw new IllegalArgumentException("empty list") 
     case h :: tail => (h, getLast(lista)) 
    } 
    } 
} 

这里它是如何工作:

scala> stackoverflow.q35804673.HeadTail.find(List(1,2,3,4,5)) 
res0: (Int, Int) = (1,5) 

scala> stackoverflow.q35804673.HeadTail.find(List(1,5)) 
res1: (Int, Int) = (1,5) 

scala> stackoverflow.q35804673.HeadTail.find(List(1)) 
res2: (Int, Int) = (1,1) 

scala> stackoverflow.q35804673.HeadTail.find(List.empty) 
java.lang.IllegalArgumentException: empty list