“模式匹配”关于可输入类型

发布于 2024-11-05 15:58:35 字数 356 浏览 0 评论 0原文

例如,假设我们有以下数据结构:

data Foo = Bool Bool | Int Int | Double Double

现在,有没有更简单的方法来做到这一点:

foo :: Typeable a => a -> Foo
foo x = maybe (error "i dunno") id $
  liftM Bool   (cast x) `mplus`
  liftM Int    (cast x) `mplus`
  liftM Double (cast x)

有人考虑过为 Typeable 类型创建模式匹配语法吗?

Suppose, for example, we have the following data structure:

data Foo = Bool Bool | Int Int | Double Double

Now, is there an easier way to do this:

foo :: Typeable a => a -> Foo
foo x = maybe (error "i dunno") id $
  liftM Bool   (cast x) `mplus`
  liftM Int    (cast x) `mplus`
  liftM Double (cast x)

Has someone thought of making a syntax for pattern matching on Typeable types?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一梦浮鱼 2024-11-12 15:58:35

使用 typeOf 和守卫:

foo x
    | tx == typeOf "str" = "string"
    | tx == typeOf True  = "bool"
    | otherwise          = "i dunno"
  where tx = typeOf x

Use typeOf and guards:

foo x
    | tx == typeOf "str" = "string"
    | tx == typeOf True  = "bool"
    | otherwise          = "i dunno"
  where tx = typeOf x
若相惜即相离 2024-11-12 15:58:35

您可以在这里使用视图模式,它们是非常方便的扩展。

{-# LANGUAGE ViewPatterns #-}

import Data.Data

data Foo = Bool Bool | Int Int | Double Double
         deriving (Show)

foo :: Typeable a => a -> Foo
foo (cast -> Just x) = Int x
foo (cast -> Just x) = Bool x
foo (cast -> Just x) = Double x
foo _ = error "i dunno"

结果:

*Main> :l foo_typeable.hs 
[1 of 1] Compiling Main             ( foo_typeable.hs, interpreted )
Ok, modules loaded: Main.
*Main> foo "123"
*** Exception: i dunno
*Main> foo 1
*** Exception: i dunno
*Main> foo (1 :: Int)
Int 1
*Main> foo (1 :: Integer)
*** Exception: i dunno
*Main> foo (1 :: Double)
Double 1.0

You can use view patterns here, they are quite handy extension.

{-# LANGUAGE ViewPatterns #-}

import Data.Data

data Foo = Bool Bool | Int Int | Double Double
         deriving (Show)

foo :: Typeable a => a -> Foo
foo (cast -> Just x) = Int x
foo (cast -> Just x) = Bool x
foo (cast -> Just x) = Double x
foo _ = error "i dunno"

Results:

*Main> :l foo_typeable.hs 
[1 of 1] Compiling Main             ( foo_typeable.hs, interpreted )
Ok, modules loaded: Main.
*Main> foo "123"
*** Exception: i dunno
*Main> foo 1
*** Exception: i dunno
*Main> foo (1 :: Int)
Int 1
*Main> foo (1 :: Integer)
*** Exception: i dunno
*Main> foo (1 :: Double)
Double 1.0
忆悲凉 2024-11-12 15:58:35

此版本不限于 BoolIntDouble,但 String 会显示为 <代码>[字符]。

foo :: Typeable a => a -> String
foo = show . typeOf

This version doesn't limit itself to Bool, Int, or Double, but a String comes out as [Char].

foo :: Typeable a => a -> String
foo = show . typeOf
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文