Haskell:按属性查找列表中的对象

Haskell:按属性查找列表中的对象,haskell,pattern-matching,Haskell,Pattern Matching,有没有办法通过一个给定的“对象”的属性来找到它? 我尝试了模式匹配,就像我在逻辑编程中所做的那样,但我无法理解: data Object = Object { _prop1 :: type, _prop2 :: color, _prop3 :: pos } deriving Eq type Square = Maybe Object type Board = [[Square]] objectlist::Board objectlist = [[ Just (Obje

有没有办法通过一个给定的“对象”的属性来找到它? 我尝试了模式匹配,就像我在逻辑编程中所做的那样,但我无法理解:

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-dim列表。

您可以使用它来获得某种效果

index_of :: (Int, Int)->Int
index_of (x,y) = fromJust $ findIndex piece objectlist
  where
    piece (Piece _ _ pos) = pos == (x,y)
你可以用它来达到那种效果

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

正如您在另一篇评论中所述,您正在2D列表中查找索引。因此我认为的
索引的类型应该是
(Int,Int)->(Int,Int)

在另一个答案中建议使用该函数,以帮助您对
进行索引。您需要的是它的通用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)
导入数据。列表
导入数据,也许吧
findIndex2D::(a->Bool)->[[a]]->可能(Int,Int)
findIndex2D pred xs=do
设maybeIndices=map(findIndex pred)xs

y正如您在另一篇评论中所述,您正在2D列表中查找索引。因此我认为
索引的类型应该是
(Int,Int)->(Int,Int)

在另一个答案中建议使用该函数,以帮助您对
进行索引。您需要的是它的通用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)
导入数据。列表
导入数据,也许吧
findIndex2D::(a->Bool)->[[a]]->可能(Int,Int)
findIndex2D pred xs=do
设maybeIndices=map(findIndex pred)xs

谢谢你的回答。我认为这是一个好的开始!如果我错了,请纠正我,但我认为这不适用于两个模糊列表。我遇到此错误:
•无法将类型“[Square]”与“Piece”预期类型匹配:[Piece]实际类型:Board•在“findIndex”的第二个参数中,即“($)”的第二个参数中的“initialBoard”,即表达式中的“findIndex-piece initialBoard”:fromJust$findIndex-piece initialBoard
感谢您的回答。我认为这是一个好的开始!如果我错了,请纠正我,但我认为这不适用于两个模糊列表。我遇到此错误:
•无法将类型“[Square]”与“Piece”预期类型匹配:[Piece]实际类型:Board•在“findIndex”的第二个参数中,即“($)”的第二个参数中的“initialBoard”,即表达式中的“findIndex-piece-initialBoard”:fromJust$findIndex-piece-initialBoard
正是我要找的!这将需要很长一段时间才能摆脱5年的强制性编程习惯!非常感谢。正是我要找的!这将需要很长一段时间才能摆脱5年的强制性编程习惯!非常感谢。