簡體   English   中英

取出最后一次輸入字符的Haskell函數

[英]Haskell function that takes out last occurrence of input character

我在編寫這個帶有字符和字符列表的函數時遇到了麻煩,然后消除了列表中最后一次出現的輸入字符。 我可以使用下面的函數取出第一次出現的輸入字符:

fun :: Char -> String -> String
fun c (s:ss)
 | s == c   = ss
 | otherwise = s : fun c ss
fun _ [] = []

我需要幫助的是如何修改此函數以取出輸入字符的最后一次出現,而不是第一次出現。 結果應該是fun 'c' "abcdccytrc"返回"abcdccytr"

好的,這就是我想出的:

fun :: Char -> String -> String
fun c (s:ss)
 | ((fun c ss) == ss) && (s == c) = ss
 | otherwise                      = s : fun c ss
fun _ [] = []

本質上,如果s == c ,並且其余的字符串( ss )通過在其上運行此函數而保持不變(即,它不包含字符c ),則返回剩余的字符。

如果不滿足此要求(即,字符串的其余部分至少有一次字符c ),請保留當前字符並將該函數應用於字符串的其余部分。

除此之外,我認為反轉字符串然后調用你的原始函數,然后再次反轉它,就像我在評論中建議的那樣,可能更容易理解,但那只是意見。

正如Numeri建議的那樣,通過刪除反向列表中的第一個匹配項來刪除最后一個匹配項是一種方法:

removeFirst :: Char -> String -> String
removeFirst _ [] = []
removeFirst c1 (c2:cs) = if c1 == c2 then cs else c2:removeFirst c1 cs

removeLast :: Char -> String -> String
removeLast c1 = reverse . removeFirst c1 . reverse

正如Will Ness建議的那樣,返回刪除最后一個匹配項的字符串,以及指示是否應該刪除當前事件的布爾值是另一個:

removeLast :: Char -> String -> String
removeLast c1 = snd . remLast
  where
    remLast :: String -> (Bool, String)
    remLast [] = (False, [])
    remLast (c2:cs) =
      case remLast cs of
        (True, cs') -> (True, c2:cs')
        (False, cs') -> if c1 == c2 then (True, cs') else (False, c2:cs')

暫無
暫無

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

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