【问题标题】:Haskell, replace every occurrence of the given word in the listHaskell,替换列表中给定单词的每次出现
【发布时间】:2018-01-14 06:12:55
【问题描述】:

我不知道如何更改列表中的给定单词

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

【问题讨论】:

  • subst st nd [] = [] subst st nd (x:xs) = if st == x then nd : xs else x : xs
  • 本人只是初学者,对Haskell中的递归函数不熟悉,不知道哪里做错了~
  • 你的类型签名应该是change :: Eq t => t -> t -> [t] -> [t]
  • 是的,抱歉,我刚才在那部分输入错误。应该改变 :: Eq t => t -> t -> [t] -> [t]

标签: string list haskell replace


【解决方案1】:

使用当前代码,您仅更改此列表的第一个元素(如果它与 st 匹配),并附加列表的其余部分 xs 不变。您应该将change 函数应用到列表的尾部。

【讨论】:

  • 感谢您的建议,我解决了这个问题,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
  • 2011-03-05
相关资源
最近更新 更多