2017-04-08 44 views
0

有沒有通過它的某個屬性查找給定「對象」的方法? 我試着模式匹配一​​樣,我會在邏輯編程都做,但我無法弄清楚:Haskell:按屬性查找列表中的對象

data Object = Object { 
    _prop1 :: type, 
    _prop2 :: color, 
    _prop3 :: pos 
} deriving Eq 

type Square = Maybe Object 
type Board = [[Square]] 

objectlist::Board 
objectlist = [[ Just (Object type color pos), Just (Object type color pos)] 
... 
[ Just (Object type color pos), Just (Object type color pos)] 

index_of :: (Int, Int)->Int 
index_of (x,y) = fromJust $ elemIndex piece objectlist 
    where 
     piece = Piece _ _ (x,y) 

另外,我覺得我的方法找到該指數是不好的。我用了一個簡單的列表,但無法找到如何使用2個暗淡列表來完成它。

回答

1

正如你在另一個answer您正在尋找在2D列表索引中的註釋說明。因此我認爲index_of的類型應該是(Int, Int) -> (Int, Int)

函數findIndex被推薦在另一個答案中,以幫助您製作index_of。你需要的是它的通用2D版本。這裏是你如何可以實現findIndex2D

import   Data.List 
import   Data.Maybe 

findIndex2D :: (a -> Bool) -> [[a]] -> Maybe (Int, Int) 
findIndex2D pred xs = do 
    let maybeIndices = map (findIndex pred) xs 
    y <- findIndex isJust maybeIndices 
    x <- maybeIndices !! y 
    return (x, y) 
+0

正是我在找的東西!搭乘5年的編程習慣需要很長時間!謝謝! –

1

您可以使用findIndex來獲得此效果。

index_of :: (Int, Int)->Int 
index_of (x,y) = fromJust $ findIndex piece objectlist 
    where 
    piece (Piece _ _ pos) = pos == (x,y) 
+0

謝謝您的回答。我認爲這是一個好開始!糾正我,如果我錯了,但我認爲這不適用於兩個暗淡的名單。我得到了這個錯誤: '•與'Piece'類型'[Square]'不匹配 預期類型:[Piece] 實際類型:Board •在'findIndex'的第二個參數中,即'initialBoard' 在'($)'的第二個參數中,即 'findIndex piece initialBoard' In the expression:fromJust $ findIndex piece initialBoard ' –

相關問題