haskell - 使用长 where 语句是不好的编码风格吗?

标签 haskell random coding-style where

我是 Haskell 新手,所以对编码风格了解不多。我有一个链接很多随机生成器的函数。这种代码是否被认为是不好的风格,其中我在 where 之后有大约 10 行陈述?如果是这样,有哪些替代方案?

#!/usr/bin/env runhaskell
{-# LANGUAGE UnicodeSyntax #-}
module Main where

makeDummy :: RandomGen g ⇒ [String] → FilePath → g → (FilePath, g)
makeDummy words root gen0 = (fullPath, gen7)
  where
      (numWordsInTitle, gen1) = randomR (1 :: Int, 4 :: Int) gen0 -- unused
      (title, gen2) = randomChoice words gen1
      (year, gen3) = randomR (1800 :: Int, 2100 :: Int) gen2
      (resNum, gen4) = randomChoice ["1080", "720", "480"] gen3
      (resLetter, gen5) = randomChoice ["P", "p", "i", "I"] gen4
      res = resNum ++ resLetter
      (shuffled, gen6) = shuffle [title, show year, resNum ++ resLetter] gen5
      (fileExt, gen7) = randomChoice [".mkv", ".mp4", ".ogv", ".srt", ""] gen6
      path = (++ fileExt) $ intercalate " " shuffled
      fullPath = root </> path

由于这可能是一个有点主观的主题,请限制答案以反射(reflect) Haskell 社区代码风格规范,而不是个人意见/美学。

我知道使用 getStdRandom 的可能性,但最好在这里使用纯函数。

最佳答案

根据要求,这里是如何使用 State 重写函数以最直接的方式。请注意,顶级类型签名没有改变。

makeDummy :: RandomGen g ⇒ [String] → FilePath → g → (FilePath, g)
makeDummy words root = runState $ do
    numWordsInTitle <- state $ randomR (1 :: Int, 4 :: Int) -- unused
    title <- state $ randomChoice words
    year <- state $ randomR (1800 :: Int, 2100 :: Int)
    resNum <- state $ randomChoice ["1080", "720", "480"]
    resLetter <- state $ randomChoice ["P", "p", "i", "I"]
    let res = resNum ++ resLetter
    shuffled <- state $ shuffle [title, show year, resNum ++ resLetter]
    fileExt <- state $ randomChoice [".mkv", ".mp4", ".ogv", ".srt", ""]
    let path = (++ fileExt) $ intercalate " " shuffled
    let fullPath = root </> path
    return fullPath

更常见的是,您会避免使用 state $。通过定义实用函数,例如 randomChoice已经在State单子(monad)。 (这或多或少是 MonadRandom 软件包的一部分。)

关于haskell - 使用长 where 语句是不好的编码风格吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31495362/

相关文章:

haskell - 是否可以使用迭代增量对键入的 Church 数字实现加法?

java - 每次排序使用相同的随机数组

python - 俄罗斯方 block 随机生成器 : random. 选择与排列与 random.shuffle

Git:在提交/推送之前通过过滤器运行?

swift - 我可以在 Swift 中声明函数然后定义它们的实现吗?

haskell - 如何使用注释自定义 HLint 并将我的 Haskell 包标记为安全?

haskell - 使用折叠的列表的局部最大值

list - 用箭头比较列表长度

c# - 使用不同随机数生成器的分布式计算

android - 是否有人为符合 Android 代码样式规则的 Eclipse IDE 创建了 Java 代码格式化程序配置文件?