如何解释这个函数:
friendlyValidityRange
:: CardanoEra era
-> (TxValidityLowerBound era, TxValidityUpperBound era)
-> Aeson.Value
friendlyValidityRange era = case
ShelleyTtl ttl -> object ["time to live" .= ttl]
(lowerBound, upperBound)
| isLowerBoundSupported || isUpperBoundSupported ->
object
[ ...
]
| otherwise -> Null
where
isLowerBoundSupported = isJust $ validityLowerBoundSupportedInEra era
isUpperBoundSupported = isJust $ validityUpperBoundSupportedInEra era
我认为friendlyValidityRange
函数利用了偏函数的概念,但仍然无法理解。friendlyValidityRange
的era
和(lowerBound, upperBound)
参数是如何以这种分离的方式传递的?
我试着模仿它使用跟随演示,仍然无法完成它。
module Main where
data Age = Child | Adult
-- Function that accept two agrs: Age, (weightMin, weightMax) , and return health description string
weightAnalyse :: Age -> (Int, Int) -> String
weightAnalyse age = case
Child -> ? -- how to comsume the (min, max) tuple
Adult -> ?
main :: IO ()
main = do
weightAnalyse Child (30, 60)
weightAnalyse Adult (60, 130)
您缺少模式同义词。看看第105行
{-# LANGUAGE PatternSynonyms #-}
pattern ShelleyTtl
:: SlotNo -> (TxValidityLowerBound era, TxValidityUpperBound era)
pattern ShelleyTtl ttl <-
( TxValidityNoLowerBound
, TxValidityUpperBound ValidityUpperBoundInShelleyEra ttl
)
这表明,一个元组的第一个组件是TxValidityNoLowerBound
,第二个组件是TxValidityUpperBound ValidityUpperBoundInShelleyEra ttl
,可以用作模式ShelleyTtl ttl
,ttl
绑定到正确的值。
所以ShelleyTtl ttl
在
friendlyValidityRange era = case
ShelleyTtl ttl -> object ["time to live" .= ttl]
匹配特定类型的元组!
您的weightAnalyse
并不真正匹配您引用的示例,但会沿着以下行:
{-# LANGUAGE LambdaCase, PatternSynonyms #-}
data Age = Child String | Adult
pattern ChildPattern x <- (_, Child x)
weightAnalyse :: Int -> (Int, Age) -> String
weightAnalyse id = case
ChildPattern x -> x
(a, age) -> "other"
-- The parameter id is unused and could be removed but is kept
-- to match the original version of the function.
-- *> weightAnalyse 1 (30, Child "foo")
-- "foo"
-- *> weightAnalyse 2 (60, Adult)
-- "other"