Haskell - 解释数字
我有一个号码 9877342931235。使用 Haskell,我需要将其显示为:
987-734293-123-5
我尝试过散布该列表,但当然这会在每个数字之间添加“-”。我该如何做才能产生实际结果?
I have a number 9877342931235. Using Haskell, I need to show it as:
987-734293-123-5
i've tried interspersing the list but of course that puts '-' between every digit. How would I do it to yield the actual result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个简单的通用解决方案,用于将列表拆分为指定长度的部分,然后使用指定的分隔符将它们连接在一起:
在您的情况下
splitercalate [3, 6, 3, 1] "-" $ show 9877342931235
会给你你想要的。更新:正如Antal SZ在下面的评论中指出的那样,您可以更多地实现此功能通过使用
Data.List
和Data.List.Split
中的函数简明地说:您需要安装
split
包(可能通过执行类似的操作cabal install split
),并导入intercalate
和splitPlaces
函数:这两个版本应该是等效的。如果您不介意额外的
import
和对split
包的依赖,请使用 Antal SZ - 它要好得多。Here's a simple general solution for splitting a list into parts of specified lengths and then joining them together with a specified delimiter:
In your case
splitercalate [3, 6, 3, 1] "-" $ show 9877342931235
would give you what you want.UPDATE: As Antal S-Z notes in a comment below, you can implement this function more concisely by using functions from
Data.List
andData.List.Split
:You would need to install the
split
package (probably by doing something likecabal install split
), and import theintercalate
andsplitPlaces
functions:The two versions should be equivalent. If you don't mind the extra
import
s and the dependency on thesplit
package, use Antal S-Z's—it's much nicer.好的,如果您不想使用 Data.List.Split...
import Data.List (intercalate)
splitPlaces (n:ns) x = let (h, t) = splitAt nx
在 h 中: splitPlaces ns t
splitPlaces _ x = []
splitercalate chunks sep = intercalate sep 。 splitPlace 块
你的答案是
concat 。 splitercalate [3,5,3,1] "-" $ 显示 9877342931235
OK, if you don't want to use Data.List.Split...
import Data.List (intercalate)
splitPlaces (n:ns) x = let (h, t) = splitAt n x
in h : splitPlaces ns t
splitPlaces _ x = []
splitercalate chunks sep = intercalate sep . splitPlace chunks
Your answer is then
concat . splitercalate [3,5,3,1] "-" $ show 9877342931235