2015-12-24 155 views
1

有跡象表明,我們想找到列表中的一個元素與功能a -> Bool和使用功能a -> a更換時間,這可能會導致一個新的列表:查找和替換

findr :: (a -> Bool) -> (a -> a) -> [a] -> Maybe [a] 
findr _ _ [] = Nothing 
findr p f (x:xs) 
    | p x = Just (f x : xs) 
    | otherwise = case findr p f xs of Just xs -> Just (x:xs) 
            _ -> Nothing 

有什麼功能在與此相似的主要模塊中?

+1

您可以通過在[Hoogle](https://www.haskell.org/hoogle/)或[Hayoo](http://hayoo.fh-wedel)上運行具有所需類型簽名的搜索自行回答此問題由Matchi.com提供回到)。 – Jubobs

+0

@Jubobs - 是的......其實我之前沒有成功嘗試過,這就是我發佈這個問題尋找類似實現的原因。 – FtheBuilder

回答

6

編輯:@gallais指出,你最終只改變第一個實例;我以爲你正在改變每一個例子。

這是用break :: (a -> Bool) -> [a] -> ([a], [a])完成的,它給你最長的前綴,它不滿足謂詞,其次是列表的其餘部分。

findr p f list = case break p list of 
      (xs, y : ys) -> Just (xs ++ f y : ys) 
      (_, [])  -> Nothing 
+1

在OP的問題中,'f'不是映射到所有'x',使得'p x'只有*第一個*。 – gallais

+0

@gallais:原本我以爲你錯了,但我現在可以看到你完全正確!謝謝! –

+0

無論如何,你不覺得這個函數應該在'Data.List'中嗎? – FtheBuilder

1

這個功能,當然,map,只要你可以結合你的斷言函數和替換函數的正確途徑。

findr check_f replace_f xs = map (replace_if_needed check_f replace_f) xs 

replace_if_needed :: (a -> Bool) -> (a -> a) -> (a -> a) 
replace_if_needed check_f replace_f = \x -> if check_f x then replace_f x else x 

現在你可以做的事情,如findr isAplha toUpper "a123-bc"