gpt4 book ai didi

haskell - 如果跌倒

转载 作者:行者123 更新时间:2023-12-04 08:57:02 25 4
gpt4 key购买 nike

如果在命令式语言中失败,Haskell 等效模式是什么,例如:

function f (arg, result) {
if (arg % 2 == 0) {
result += "a"
}

if (arg % 3 == 0) {
result += "b"
}

if (arg % 5 == 0) {
result += "c"
}

return result
}

最佳答案

而不是使用 State monad,你也可以使用 Writer monad 并利用 StringMonoid实例(真正的 [a]Monoid 实例):

import Control.Monad.Writer

f :: Int -> String -> String
f arg result = execWriter $ do
tell result
when (arg `mod` 2 == 0) $ tell "a"
when (arg `mod` 3 == 0) $ tell "b"
when (arg `mod` 5 == 0) $ tell "c"

我认为它非常简洁,干净,简单。

State 相比,它有一个优势。 monad 是您可以通过重新排列行来重新排列发生连接的顺序。例如,如果你想运行 f 30 "test"离开 "atestbc" ,您所要做的就是交换 do 的前两行:
f arg result = execWriter $ do
when (arg `mod` 2 == 0) $ tell "a"
tell result
when (arg `mod` 3 == 0) $ tell "b"
when (arg `mod` 5 == 0) $ tell "c"

而在 State monad 你必须改变操作:
f arg = execState $ do
when (arg `mod` 2 == 0) $ modify ("a" ++)
when (arg `mod` 3 == 0) $ modify (++ "b")
when (arg `mod` 5 == 0) $ modify (++ "c")

因此,您必须仔细检查实际操作( (++ "a")("a" ++) 之间存在细微差别),而不是在输出字符串中的执行顺序和顺序之间存在关系,而 Writer在我看来,代码乍一看非常清楚。

正如@JohnL 所指出的,这并不是一个有效的解决方案,因为在 Haskell Strings 上进行串联不是很快,但你可以很容易地使用 TextBuilder解决这个问题:
{-# LANGUAGE OverloadedStrings #-}
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.Builder as B
import Control.Monad.Writer

f :: Int -> Text -> Text
f arg result = B.toLazyText . execWriter $ do
tellText result
when (arg `mod` 2 == 0) $ tellText "a"
when (arg `mod` 3 == 0) $ tellText "b"
when (arg `mod` 5 == 0) $ tellText "c"
where tellText = tell . B.fromLazyText

因此,除了转换为更有效的类型之外,算法并没有真正的变化。

关于haskell - 如果跌倒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23430994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com