简体   繁体   English

检查它是否是特定类型-Haskell

[英]Check if it is a specific type - haskell

I thought it would be really easy to find the answer online but I had no luck with that. 我认为在网上找到答案真的很容易,但是我对此并不走运。 Which means that my question should't be a question but I am sure more people new to Haskell might come up with the same question. 这意味着我的问题不应该是一个问题,但是我敢肯定,更多对Haskell陌生的人可能会提出相同的问题。

So how do I check if a value is of a certain type? 那么,如何检查某个值是否属于某种类型?

I have the following data type defined and I wanna check whether the input on a function is of a specific type. 我定义了以下数据类型,我想检查函数的输入是否为特定类型。

data MyType a = MyInt Int | MyOther a (MyType a)

First, your data declaration will not work. 首先,您的data声明将不起作用。 Let's assume you're using this type: 假设您使用的是这种类型:

data MyType a = MyInt Int | MyOther a (MyType a)

then you can have functions that take a MyType a , some specific MyType (eg MyType Int ) or a constrained MyType (eg Num a => MyType a ). 那么您可以使用采用MyType a ,某些特定MyType (例如MyType Int )或受约束的MyType (例如Num a => MyType aNum a => MyType a

If you want to know whether you have a MyInt or a MyOther , you can simply use pattern matching: 如果你想知道你是否有一MyIntMyOther ,你可以简单地使用模式匹配:

whichAmI :: MyType a -> String
whichAmI (MyInt i) = "I'm an Int with value " ++ show i
whichAmI (MyOther _ _) = "I'm something else"

When you want to know if the type in the parameter a is a Num , or what type it is, you will run into a fundamental Haskell limitation. 当您想知道参数a的类型是Num还是什么类型时,就会遇到基本的Haskell限制。 Haskell is statically typed so there is no such dynamic checking of what the a in MyType a is. Haskell是静态类型的,因此无法对MyType aa进行动态检查。

The solution is to limit your function if you need a certain type of a . 解决的办法是,如果你需要某种类型的限制你的功能a For example we can have: 例如,我们可以有:

mySum :: Num a => MyType a -> a
mySum (MyInt i) = fromIntegral i
mySum (MyOther n m) = n + mySum m

or we can have a function that only works if a is a Bool : 或者我们可以有一个仅在aBool时才起作用的函数:

trueOrGE10 :: MyType Bool -> Bool
trueOrGE10 (MyInt i) = i >= 10
trueOrGE10 (MyOther b _) = b

As with all Haskell code, it will need to be possible to determine at compile-time whether a particular expression you put into one of these functions has the right type. 与所有Haskell代码一样,有必要在编译时确定放入这些函数之一的特定表达式是否具有正确的类型。

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

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