我想在Haskell中編程成本函數,但似乎我高估了模式匹配的功能。這是我已經定義的代碼:編程成本函數的最佳方式(相關函數 - 值)
-- Directions for the movement
data Direction = North | East | West | South deriving (Show, Eq)
-- An `Action` gets a Coord and returns another Coord if possible
type Action = Coord -> Maybe Coord
-- Move function; `move North` is an Action
move :: Direction -> Action
move d (x, y) = ...
我的主要問題是,現在我必須定義一個Cost
功能使得:
type Cost = Coord -> Action -> Double
在情況下,我想有一個簡單的成本函數只檢查方向返回一個成本,即來到了我的腦海裏第一個想法是利用模式匹配的,但這是無效的語法(和說實話,它似乎很公平):
mazeCost :: Cost
mazeCost (x, y) (move East) = 3
mazeCost (x, y) (move West) = 5
-- ... And on and on
我目前的解決方案涉及到計算目標狀態,並將其與每個操作的結果進行比較,以檢查這是否是作爲參數傳遞的函數,但這看起來很亂,並不是超級簡短的,我認爲也許有很多更好的方式來做到這一點在Haskell:
mazeCost :: Cost
mazeCost coord action
| destination == east = 1
| destination == west = 2
| destination == north = 3
| destination == south = 0
where destination = action coord
east = move East coord
west = move West coord
south = move South coord
north = move North coord
有沒有更好的方式與成本值(Double
)的函數(Coord -> Direction -> Maybe Coord
)相關聯?這是我試圖編寫的一個簡單示例,如果示例代碼中存在任何不一致或者不清楚,請詢問。
如果'destination'不是四個主要方向之一?例如。如果它是「移動」的組合? – luqui
爲什麼用移動的結果而不是選定的方向來表示動作,這將允許您進行模式匹配? –
@ Li-yaoXia這正是我想要做的,但是我現在傳遞給函數的是已經部分應用的函數,比如'move East'。這是我試圖模式匹配,但我不知道「解壓」這些值的語法 –