簡體   English   中英

Haskell,替換列表中給定單詞的每次出現

[英]Haskell, replace every occurrence of the given word in the list

我被困在如何更改列表中的給定單詞

change :: Eq t => t -> t -> [t] -> [t]
change x y z

該函數應像給單詞x並在z列表中將其替換為y一樣工作。

例如change 'a' 'c' "banana" ,結果將是"bcncnc"

我應該如何遞歸檢查列表並更改單詞的每次出現?

我自己的嘗試:

change st nd [] = []
change st nd (x:xs) = if st == x then nd : xs else x : xs

使用當前代碼,您僅更改此列表的第一個元素(如果它與st匹配),並且將其余列表xs保持不變。 您應該將change功能應用於列表的末尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM