gpt4 book ai didi

haskell - 尝试摆脱嵌套表达式

转载 作者:行者123 更新时间:2023-12-02 13:20:46 26 4
gpt4 key购买 nike

我有一个 yaml 文件:

base123:
key1: "key1"
key2: "key2"
key3: "key3"

以及应该从中读取所有 3 个值的代码:

read123 :: IO (String, String, String)
read123 = do
rawConfig <- Y.decodeFile "config.yml" :: IO (Maybe Y.Value)
case rawConfig of
Just res1 ->
case res1 of
Object res2 ->
case (LHashMap.lookup "base123" res2) of
Just (Object res3) ->
case (LHashMap.lookup "key1" res3) of
Just (String key1) ->
case (LHashMap.lookup "key2" res3) of
Just (String key2) ->
case (LHashMap.lookup "key3" res3) of
Just (String key3) -> return (key1, key2, key3)
_ -> error "some error"

Nothing -> error "error123"

看起来效果不错。但我相信,一定有一种方法可以在不使用 Lens 的情况下摆脱嵌套表达式。有没有?或者有什么方法可以更简单地完成同样的事情?

更新:

  rawConfig <- Y.decodeFile "config.yml" :: IO (Maybe Y.Value)
case rawConfig of
Just (Object res1) -> LHashMap.lookup "base123" res1
Nothing -> error "error"

return ("", "", "") -- stub

错误:

Couldn't match type `Maybe' with `IO'
Expected type: IO Value
Actual type: Maybe Value
In the return type of a call of `LHashMap.lookup'

最佳答案

我建议您使用正确的数据类型来存储 YAML 数据。迈克尔·斯诺曼的yaml库重用了 aeson 的大部分 API。所以它与使用 aeson 包的方式非常相似。这是一个有效的示例代码:

{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative
import Control.Monad (mzero)
import Data.Text
import Data.Yaml

data Base = Base {
key1 :: Text,
key2 :: Text,
key3 :: Text
} deriving (Show)

instance FromJSON Base where
parseJSON (Object v) = Base <$>
((v .: "base123") >>= (.: "key1")) <*>
((v .: "base123") >>= (.: "key2")) <*>
((v .: "base123") >>= (.: "key3"))

parseJSON _ = mzero

main = do
b <- decodeFile "/home/sibi/yaml.yml" :: IO (Maybe Base)
print b

在 ghci 中:

λ> main
Just (Base {key1 = "key1", key2 = "key2", key3 = "key3"})

关于haskell - 尝试摆脱嵌套表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24973253/

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