gpt4 book ai didi

haskell - 传递类型以在 haskell 中解码 json

转载 作者:行者123 更新时间:2023-12-03 23:04:56 26 4
gpt4 key购买 nike

我认为我正在以一种根本不正确的方式解决这个问题,但我不确定如何在 Haskell 中做出优雅的解决方案。

我想编写一个函数,将 JSON 字符串解析为某种 Haskell 类型。但是,我不知道如何将类型传递到我的函数中(我认为我做不到)。

例如,我想做这样的事情:

data Foo = Foo { _a :: String } deriving (Generic, ToJSON, FromJSON)
data Bar = Bar { _b :: String } deriving (Generic, ToJSON, FromJSON)

parseSomething :: (FromJSON a) => a -> Maybe a
parseSomething a = (decode "..some json string...") :: Maybe a

这可能吗,还是我对问题的思考不正确?

此刻,我收到一个类型推导错误:

    • Could not deduce (FromJSON a1) arising from a use of ‘decode’
from the context: FromJSON a
bound by the type signature for:
foo :: forall a. FromJSON a => a -> Maybe a
at src/Plumbing/Types.hs:60:1-35
Possible fix:
add (FromJSON a1) to the context of
an expression type signature:
forall a1. Maybe a1
• In the expression: decode "{\"_a\":\"foo\"}" :: (Maybe a)
In an equation for ‘foo’:
foo a = decode "{\"_a\":\"foo\"}" :: (Maybe a)
|
61 | foo a = decode "{\"_a\":\"foo\"}" :: (Maybe a)

最佳答案

您可以使用 type applications对此的扩展:

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}

import Data.Aeson
import GHC.Generics

data Foo = Foo { _a :: String } deriving (Show, Generic, ToJSON, FromJSON)
data Bar = Bar { _b :: String } deriving (Show, Generic, ToJSON, FromJSON)

parseSomething :: (FromJSON a) => Maybe a
parseSomething = decode "{ \"_a\": \"Hello\" }"

main :: IO ()
main = putStrLn $ show (foo, bar)
where
foo = parseSomething @Foo
bar = parseSomething @Bar

但老实说,我认为能够写作的好处为零

foo = parseSomething @Foo
bar = parseSomething @Bar

结束

foo = parseSomething :: Maybe Foo
bar = parseSomething :: Maybe Bar

关于haskell - 传递类型以在 haskell 中解码 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63293015/

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