gpt4 book ai didi

Haskell:如何解开数据中嵌套的可能

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

这里是新手!

假设我有以下数据:

data Supplier = Supplier { 
nameS :: String,
country :: Maybe String
}

data Product = Product {
nameP :: String,
supplier :: Maybe Supplier
}

我需要一个函数来返回 Maybe 产品的国家/地区,或者如果链中没有 Nothing,则返回“未知”。我可以这样做:

productCountry :: Maybe Product -> String
productCountry product =
case product of
Just p -> case supplier p of
Just s -> case country s of
Just c -> c
Nothing -> "unknown"
Nothing -> "unknown"
Nothing -> "unknown"

但这很尴尬。另一种方法是:

import Data.Maybe (fromMaybe)

productCountry2 :: Maybe Product -> String
productCountry2 product =
let countryMaybe = do
p <- product
s <- supplier p
c <- country s
return c
in fromMaybe "unknown" countryMaybe

我觉得一定有更好的方法,但我找不到。

“productCountry”的最佳惯用 Haskell 代码是什么?

最佳答案

如果您正在编写一个第一个参数为 Maybe Something 类型的函数,这通常是一个好兆头,表明您不必要地避免 Maybe 的 monad 实例。

data Supplier = Supplier { 
nameS :: String,
country :: Maybe String
}

data Product = Product {
nameP :: String,
supplier :: Maybe Supplier
}

productCountry :: Product -> Maybe String
productCountry p = supplier p >>= country
-- Or, using Kleisli composition (requires Control.Monad)
-- productCountry = supplier >=> country

如果您发现自己有一个 Maybe Product 实例,请再次使用 Maybe monad 将其提供给 productCountry

maybeProduct >>= productCountry  -- Just "somelandia" or Nothing

此外,让任何调用 productCountry 担心如果他们返回什么都没有,是否需要占位符国家/地区名称。

关于Haskell:如何解开数据中嵌套的可能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55546863/

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