简体   繁体   English

Haskell 模式匹配类型

[英]Haskell pattern match on type

Is there any way of doing something like this in haskell?有没有办法在 haskell 中做这样的事情?

data Fruits = Apple Int | Orange Int deriving (Eq, Show)

basket = [Apple 2, Orange 4]

from_basket t (x:basket) =
    case x of
        (t i) -> i
        _ -> from_basket t basket

Now i want to get the 'apple' from the list of fruits ( basket )现在我想从水果列表(篮子)中获取“苹果”

from_basket Apple basket

Without an explicit pattern match没有明确的模式匹配

case x of
    Apple i -> ...
    Orange i -> ...
    _ ->

One way would be to define your own helper function isApple and then do filtering:一种方法是定义您自己的助手 function isApple然后进行过滤:

isApple (Apple _) = True
isApple _         = False

getApples = filter isApple

Pattern matching is the tool of your choice, I don't know whether you can simplify this any further.模式匹配是您选择的工具,我不知道您是否可以进一步简化它。 But apart from some dirty template Haskell, I don't see any other way.但除了一些脏模板 Haskell 之外,我没有看到任何其他方式。

The other answers have explained why it won't work as is, but as far as alternatives go, wanting to do something like that is often a sign that your data types should look something more like this:其他答案已经解释了为什么它不能按原样工作,但就替代方案 go 而言,想要做类似的事情通常表明您的数据类型应该看起来更像这样:

data FruitName = Apple | Orange deriving (Eq, Show)
data Fruits = Fruits FruitName Int deriving (Eq, Show)

...in which case the desired function becomes trivial. ...在这种情况下,所需的 function 变得微不足道。

You can accomplish something similar to this by defining selector functions您可以通过定义选择器函数来完成类似的事情

getApple :: Fruits -> Maybe Int
getApple (Apple x) = Just x
getApple _ = Nothing

getOrange :: Fruits -> Maybe Int
getOrange (Orange x) = Just x
getOrange _ = Nothing

fromBasket selector [] = Nothing
fromBasket selector (x:basket) =
    case selector x of
        Just x -> Just x
        Nothing -> fromBasket selector basket

Now you can do现在你可以做

> fromBasket getApple basket
Just 2

> fromBasket getOrange basket
Just 4 

This assumes that your constructors all take similar arguments.这假设您的构造函数都采用类似的 arguments。 It also returns Nothing if the desired fruit type was not in the basket.如果所需的水果类型不在篮子中,它也会返回Nothing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM