2013-10-28 156 views
1

我在Haskell中生成一個州的鄰居。生成一個州的鄰居列表

狀態是行的列表。這些操作可以在一行中獨立執行。每行都會調用一個函數,該函數返回該行的一組鄰居。

下面是一個例子(我會讓行是爲了簡單字符):

state = ['a', 'b', 'c'] 
rowNeighbours a = ['x', 'y'] 
rowNeighbours c = ['p', 'q'] 
rowNeighbours _ = [] 

neighbours應該呼籲各行rowNeighbours並生成狀態[['x', 'b', 'c'], ['y', 'b', 'c'], ['a', 'b', 'p'], ['a', 'b', 'q']]的列表。

我在生成此列表時遇到問題。以下是我提出的解決方案。

neighbours state = 
[ [x, y, z] | x <- rowNeighbours (state !! 0), y <- [state !! 1], z <- [state !! 2] ] ++ 
[ [x, y, z] | x <- [state !! 0], y <- rowNeighbours (state !! 1), z <- [state !! 2] ] ++ 
[ [x, y, z] | x <- [state !! 0], y <- [state !! 1], z <- rowNeighbours (state !! 2) ] 

它的工作原理,但我的實際問題有「6」行,所以這變得相當不雅,看上去就像一個非功能性的方式來做事。我很感激任何關於如何去做這件事的指示,謝謝。

回答

2

我認爲這會做你想要什麼:

neighbors (s:tate) = map (: tate) (rowNeighbors s) ++ map (s :) (neighbors tate) 
neighbors [] = []