2015-04-22 66 views
2

我試圖使用下面的代碼展開列表的列表。當我把它放在紙上時,它應該起作用,但我認爲我誤解了或者對列表的工作方式一無所知。任何人都可以告訴我我錯了哪裏。在Scala中使用展平方法給出了糟糕的結果,列出了列表中的列表

val a = List(List(1,2,3),List(4,5,6),List(7,8,9)) 

def flatten(xss : List[List[Any]]) : List[Any] = { 
    def flat(xs : List[Any]) : List[Any] = xs match { 
    case Nil => Nil 
    case head :: Nil=> head :: Nil 
    case head :: tail => head :: flat(tail) 
    } 
    xss match { 
    case Nil => Nil 
    case head :: Nil => flat(head) 
    case head :: tail => flat(head) :: flatten(tail) 
    } 
} 

flatten(a) 
+0

我認爲你需要採取另一種思維會話什麼壓扁列表意味着,一個好的技巧我傾向於使用的表達出來換句話說,因爲經常有一個功能實現匹配那麼好。 – johanandren

+0

你有沒有想過使用內置的flatMap函數? – Leon

+0

我應該實現扁平化功能而不使用扁平化方法。即使不應該使用::: – user64287

回答

0

實際上,你可以模式匹配深入到結構:

def flatten[T](xss: List[List[T]]): List[T] = xss match { 
    case Nil => Nil 
    case Nil :: tail => flatten(tail) 
    case (innerHead :: innerTail) :: tail => innerHead :: flatten(innerTail :: tail) 
} 
+0

這是執行工作的非常有效的方式。你還可以看看我的代碼,並告訴我哪裏出了問題。同樣從代碼中,當我用'head :: Nil => flatten(head)'替換第二個case時,它確實會產生差異(錯誤)。無論如何,它對列表中的最後一個值有什麼不同。 – user64287

+0

我知道頭返回原始類型,作爲尾部返回一個List。類型不匹配是阻止我執行其他方法的一個問題。 – user64287

+0

@Ram_TU是的,類型給了錯誤。對於'List [T]','::'的左邊有'T'類型,右邊有'List [T]'類型。在你的原始版本中,你有'case head :: tail => flat(head):: flatten(tail)',但是flat(head)的返回類型不是一個單獨的列表。 – Tilo

1

您的flat函數只是重新創建了它的參數列表,因此它可以被刪除。

你只需要連接內部列表,使用:::

def flatten(xss : List[List[_]]): List[Any] = xss match { 
    case Nil => Nil 
    case head :: tail => head ::: flatten(tail) 
} 
1

我做了兩個小的改動你的榜樣,使其能工作。第一個是使用通用的(不是問題,但清除了一些代碼)。第二種是在輸入列表具有多個項目的情況下使用:::而不是::::方法將單個項目預加到列表中,該列表是列表中項目的類型。 :::將兩個列表連接在一起。使用一種List[Any],您無法看到該問題。但是,一旦我將其類型更改爲T,問題出現的位置非常清楚。

def flatten[T](xss : List[List[T]]) : List[T] = { 
    def flat(xs : List[T]) : List[T] = xs match { 
    case Nil => Nil 
    case head :: Nil=> head :: Nil 
    case head :: tail => head :: flat(tail) 
    } 
    xss match { 
    case Nil => Nil 
    case head :: Nil => flat(head) 
    case head :: tail => flat(head) ::: flatten(tail) 
    } 
} 
+0

我應該實現扁平化功能而不使用扁平化方法。即使不應該使用::: – user64287