Haskell - 有一个函数返回一个空字符 [英] Haskell - have a function return an empty character
问题描述
dropEvery :: String 我试图创建一个从字符串中删除每个第n个元素的函数。 - > Int - > String
dropEvery str n = map(\(char,indx) - > if indx`mod` n / = 0 then char else'')(zip str [1 ..])
现在它只是用空格替换每个第n个元素,但是我应该在else如果我想让它返回一个空字符。我明白,Haskell中不存在这样的事情,所以问题是 - 我该如何告诉Haskell不返回任何内容并转到下一个字符?
concatMap
,您可以在没有太多更改的情况下运行。该函数需要您映射的函数返回一个列表,然后将所有结果连接在一起。所有你需要做的是pre $ drop $ $
concatMap(\(char,indx) - > if indx`mod` n / = 0 then [char] else [])(zip str [1 ..])
I'm trying to create a function that drops every n'th element from a string.
dropEvery :: String -> Int -> String
dropEvery str n = map (\(char, indx) -> if indx `mod` n /= 0 then char else ' ') (zip str [1..])
Right now it simply replaces every n'th element with a space, but what am I supposed to put after the "else" if I want it to return an "empty char". I understand that such a thing doesn't exist in Haskell so the question is - how am I supposed to tell Haskell to not return anything and just move on to the next char?
You can't do this with just map
, by definition it can't change the length of the collection it's applied to. However, you can get this to work without too many changes by switching to concatMap
. This function requires the your function that you're mapping return a list, then it concatenates all the results together. All you'd need to do is
dropEvery str n =
concatMap (\(char, indx) -> if indx `mod` n /= 0 then [char] else []) (zip str [1..])
这篇关于Haskell - 有一个函数返回一个空字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!