Haskell - 解释数字

发布于 2024-09-03 21:57:37 字数 125 浏览 4 评论 0原文

我有一个号码 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

可爱暴击 2024-09-10 21:57:37

这是一个简单的通用解决方案,用于将列表拆分为指定长度的部分,然后使用指定的分隔符将它们连接在一起:

splitercalate :: [Int] -> [a] -> [a] -> [a]
splitercalate (x:[]) _     s = take x s
splitercalate (x:xs) delim s =
  case splitAt x s of
    (a, []) -> a
    (a, bs) -> a ++ delim ++ splitercalate xs delim bs

在您的情况下 splitercalate [3, 6, 3, 1] "-" $ show 9877342931235会给你你想要的。

更新:正如Antal SZ在下面的评论中指出的那样,您可以更多地实现此功能通过使用 Data.ListData.List.Split 中的函数简明地说:

splitercalate chunks sep = intercalate sep . splitPlaces chunks

您需要安装 split 包(可能通过执行类似的操作cabal install split),并导入 intercalatesplitPlaces 函数:

import Data.List (intercalate)
import Data.List.Split (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:

splitercalate :: [Int] -> [a] -> [a] -> [a]
splitercalate (x:[]) _     s = take x s
splitercalate (x:xs) delim s =
  case splitAt x s of
    (a, []) -> a
    (a, bs) -> a ++ delim ++ splitercalate xs delim bs

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 and Data.List.Split:

splitercalate chunks sep = intercalate sep . splitPlaces chunks

You would need to install the split package (probably by doing something like cabal install split), and import the intercalate and splitPlaces functions:

import Data.List (intercalate)
import Data.List.Split (splitPlaces)

The two versions should be equivalent. If you don't mind the extra imports and the dependency on the split package, use Antal S-Z's—it's much nicer.

廻憶裏菂餘溫 2024-09-10 21:57:37

好的,如果您不想使用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文