Haskell - 有一个函数返回一个空字符 [英] Haskell - have a function return an empty character

查看:103
本文介绍了Haskell - 有一个函数返回一个空字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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不返回任何内容并转到下一个字符?

map 来做到这一点,根据定义,它不能改变它应用到的集合的长度。但是,通过切换到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆