Haskell从IO中提取长度(回复[Data.ByteString.Internal.ByteString])

Haskell从IO中提取长度(回复[Data.ByteString.Internal.ByteString]),haskell,redis,Haskell,Redis,需要从一个已经离开的开发者那里修补一个Haskell项目,但我是一个完全的Haskell Noob 尝试编写一个函数,返回与模式匹配的所有Redis键的计数。从交互角度看,它如下所示: *MyProj S R U>let res = runRedis conn $ keys "MP:Users*" *MyProj S R U> res Right ["MP:Users:00:13:95:12:7D:85","MP:Users:00:13:95:12:7D:84","MP:Users:

需要从一个已经离开的开发者那里修补一个Haskell项目,但我是一个完全的Haskell Noob

尝试编写一个函数,返回与模式匹配的所有Redis键的计数。从交互角度看,它如下所示:

*MyProj S R U>let res = runRedis conn $ keys "MP:Users*"
*MyProj S R U> res
Right ["MP:Users:00:13:95:12:7D:85","MP:Users:00:13:95:12:7D:84","MP:Users:APP"]
*MyProj S R U> :t res
res :: IO (Either Reply [Data.ByteString.Internal.ByteString])
因此,在本例中,我只需要从Redis获得正确的ByteString数组响应的长度。3在这种情况下。如果出现任何问题或没有响应,此函数只能返回0

我真的不知道如何在Haskell做到这一点,我能想到的最接近的事情是:

redisKeyCount :: Connection -> BSC.ByteString -> IO Int
redisKeyCount conn keypattern =
  runRedis conn $ do
    response <- keys keypattern
    case response of
      [BSC.ByteString] allkeys ->
        case length allkeys of
          Just (n, _) -> return n
          _           -> return 0
      _ -> return 0
redisKeyCount::Connection->BSC.ByteString->IO Int
redisKeyCount连接键模式=
runRedis conn$do
回应
大小写所有键
只需(n,)->返回n
_->返回0
_->返回0

但是,这当然行不通。我已经尝试了上述的几十种变体。如何提取并返回此res::IO右侧的长度(或者回复[Data.ByteString.Internal.ByteString])?

您已经接近了!关键是使您的模式匹配
响应
匹配其类型。由于
keys-keyptern::IO(任意回复[ByteString])
response
的类型为
任意回复[ByteString]

任何一个b
都有两个构造函数-
Left::a->a b
Right::b->a b
,当我们使用
case
解构
任何一个b
值时,可以匹配这些模式

redisKeyCount :: Connection -> BSC.ByteString -> IO Int
redisKeyCount conn keypattern =
  runRedis conn $ do
    response <- keys keypattern
    return $ case response of
      Left _reply -> 0
      Right allKeys -> length allKeys
redisKeyCount::Connection->BSC.ByteString->IO Int
redisKeyCount连接键模式=
runRedis conn$do
答复0
右键所有键->长度所有键

从@rampion的答案开始进行详细阐述:

redisKeyCount :: Connection -> BSC.ByteString -> IO Int
redisKeyCount conn keypattern =
  runRedis conn $ do
    response <- keys keypattern
    return $ case response of
      Left _reply -> 0
      Right allKeys -> length allKeys
然后,
xbsc.ByteString->ioint
redisKeyCount连接键模式=
runRedis conn(任意(常量0)长度键键模式)

谢谢你的回答。当我尝试这样做时,在右边的行中出现了一个错误:library/Redis.hs:66:24:无法将表达式中的预期类型“Redis Int”与实际类型“Int”匹配:length allKeys In a case alternative:Right allKeys->length allKeys dave Collins:d'oh。这就是我在没有编译的情况下回答问题的原因。修正(希望)非常感谢!!我现在正在大力崇拜哈斯克尔!
redisKeyCount :: Connection -> BSC.ByteString -> IO Int
redisKeyCount conn keypattern =
  runRedis conn $ do
    response <- keys keypattern
    return $ either (const 0) length response
redisKeyCount :: Connection -> BSC.ByteString -> IO Int
redisKeyCount conn keypattern =
  runRedis conn (either (const 0) length <$> keys keypattern)