下面是與列表一個可能的解決方案,以下類型的:
f :: Eq a => [a] -> [a] -> [Maybe a]
我會叫列表中搜索haystack
和搜索needles
的元素。首先,我們可以搜索haystack
每個needle
,並返回一對價值和它被發現的,如果任何指標,用findIndex
:
findIndices needles haystack =
[ (needle, findIndex (== needle) haystack)
| needle <- needles
]
findIndices [1, 3] xs == [(1, Just 4), (3, Just 2)]
(請注意,這總是使用第一的指數發生 - 我不知道這是你想要的你可以擴展它放到倍,因爲它的發現,除去每次出現)
然後通過索引排序,這份名單:。
sortBy (comparing snd) [(1, Just 4), (3, Just 2)]
==
[(3, Just 2), (1, Just 4)]
最後提取,這是實際存在的每個指標的值,使用(<$) :: Functor f => a -> f b -> f a
:
[value <$ mIndex | (value, mIndex) <- [(3, Just 2), (1, Just 4)]]
==
[Just 3, Just 1]
(x <$ f
相當於const x <$> f
)
可是當我們嘗試這種對輸入其中的一些元素AREN」 t上找不到,我們得到錯誤的結果,其中Nothing
小號來一開始,而不是結束:
findIndices [9, 1] xs == [(9, Nothing), (1, Just 4)]
sortBy (comparing snd) [(9, Nothing), (1, Just 4)]
==
[(9, Nothing), (1, Just 4)]
這是因爲Nothing
被認爲小於任何Just
值。由於我們希望相反,我們可以利用Data.Ord
的Down
NEWTYPE,通過傳遞Down . snd
代替snd
作爲比較扭轉Maybe
的排序順序:
sortBy (comparing (Down . snd)) [(9, Nothing), (1, Just 4)]
==
[(1, Just 4), (9, Nothing)]
但這也反轉的排序順序指數本身,這是我們不希望:
sortBy (comparing (Down . snd)) [(1, Just 4), (3, Just 2)]
==
[(1, Just 4), (3, Just 2)]
因此,我們可以添加另一Down
圍繞指數:
findIndices needles haystack =
[ (needle, Down <$> findIndex (== needle) haystack)
| needle <- needles
]
sortBy (comparing Down) [Just (Down 2), Nothing, Just (Down 1)]
==
[Just (Down 1), Just (Down 2), Nothing]
sortBy (comparing (Down . snd))
[(1, Down (Just 4)), (3, Down (Just 2))]
==
[(3, Down (Just 2)), (1, Down (Just 4))]
最後把它放在一起:
f :: (Eq a) => [a] -> [a] -> [Maybe a]
f needles haystack =
[ value <$ index
| (value, index) <- sortBy (comparing (Down . snd))
[ (needle, Down <$> findIndex (== needle) haystack)
| needle <- needles
]
]
f [1, 3] xs == [Just 3, Just 1]
f [3, 1] xs == [Just 3, Just 1]
f [1, 9] xs == [Just 1, Nothing]
f [9, 9] xs == [Nothing, Nothing]
,或雖未列表內涵與較短的名稱:
f :: (Eq a) => [a] -> [a] -> [Maybe a]
f ns hs
= map (\ (v, i) -> v <$ i)
$ sortBy (comparing (Down . snd))
$ map (\ n -> (n, Down <$> findIndex (== n) hs)) ns
\ (v, i) -> v <$ i
也可以寫爲uncurry (<$)
,但是這可能會有點神祕,如果你不習慣於無點的風格。另外,如果您不關心Nothing
,則可以使用mapMaybe
而不是map
,將返回類型從[Maybe a]
更改爲僅[a]
。