Haskell中的类型比较 [英] Type comparison in Haskell

查看:92
本文介绍了Haskell中的类型比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还在学习Haskell的基础知识,并且试图找到这个简单问题的答案,所以我提前道歉,因为我确信它很简单。



鉴于:

  data Fruit = Fruit | Apple | Orange 
derived(Show,Eq)

a = Apple

如何检查一个a是否为Fruit?

解决方案

假设您确实是指 type 比较,简单的答案是你不能。 Haskell是静态类型的,所以检查是在编译时完成的,而不是运行时完成的。所以,如果你有这样的功能:

  foo :: Fruit  - > Bool 
foo Apple = True
foo x = False

答案是否或者不是 x 是一个水果永远是是。



你可能试图做的是找到了解构建给定值的数据构造函数。要做到这一点,请使用模式匹配:

  fruitName :: Fruit  - > String 
fruitName Fruit =Fruit
fruitName Apple =Apple
fruitName Orange =Orange

顺便说一下,如果您使用的是GHCi,并且您想知道某种类型的东西,请使用:t

 >让a = 123 
> :t a
a :: Integer
>


I'm still just learning the basics of Haskell, and I've tried to find an answer to this simple question, so I apologize in advance, because I'm sure it's simple.

Given:

data Fruit = Fruit| Apple | Orange
    deriving (Show, Eq)

a = Apple

How do I check if some a is a Fruit?

解决方案

Assuming you really meant type comparison, the simple answer is "you can't". Haskell is statically typed, so the check is done at compile-time, not run-time. So, if you have a function like this:

foo :: Fruit -> Bool
foo Apple = True
foo x     = False

The answer of whether or not x is a Fruit will always be "yes".

What you might be trying to do is find out what data constructor a given value was constructed with. To do that, use pattern matching:

fruitName :: Fruit -> String
fruitName Fruit  = "Fruit"
fruitName Apple  = "Apple"
fruitName Orange = "Orange"

By the way, if you're using GHCi, and you want to know the type of something, use :t

> let a = 123
> :t a
a :: Integer
>

这篇关于Haskell中的类型比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆