繁体   English   中英

在haskell中定义自定义类型

[英]custom type define in haskell

我是haskell的新手,我定义了一个自定义列表类型,但是当我尝试定义此函数mymaximum时。 我注意到,仅当a为Num类型时才有效。 如果我希望它可以与所有类型(例如Char)一起使用,应该怎么更改?

data List a = ListNode a (List a) | ListEnd

mymaximum::List a -> a
mymaximum ListEnd = 0
mymaximum (ListNode x xs) 
    |  x > maxxs = x
    | otherwise = maxxs
    where maxxs = mymaximum xs

首先,如果您尝试按照给出的定义加载定义,则会收到错误消息,

....
 No instance for (Num a) arising from the literal `0'
 Possible fix:
   add (Num a) to the context of
     the type signature for mymaximum :: List a -> a
....

因此,这表明您需要将类型签名更改为

mymaximum :: (Num a) => List a -> a

现在错误消息是

....
Could not deduce (Ord a) arising from a use of `>'
from the context (Num a)
  bound by the type signature for mymaximum :: Num a => List a -> a
  at <interactive>:59:14-35
Possible fix:
  add (Ord a) to the context of
    the type signature for mymaximum :: Num a => List a -> a
....

同样,我们将类型签名更改为

mymaximum :: (Num a, Ord a) => List a -> a

现在,GHCi响应:

mymaximum :: (Num a, Ord a) => List a -> a

意思是,它接受了带有类型签名的定义。

现在,此功能将适用于同时实现NumOrd类型类的所有类型。

Int是一个, Float是另一个。 Char不是。 但是,如果import Data.Char ,则可以使用这些功能

chr :: Int -> Char

ord :: Char -> Int

要解决此问题,请在您的List Char值上映射ord (您还必须为此定义自己的map函数...也许),找到最大值,然后与chr一起工作以恢复字符。

更新:正如您所注意到的,特殊的大小写0作为空白列表的最大值不是正确的事情。 将单元素列表作为您的基本案例是一个很好的解决方案。 现在可以删除Num a约束,并且该函数也将按List Char参数的形式工作,或者任何Ord a => List aOrd a => List a类型,从而产生Ord a => aOrd a => a类型。

有一点需要注意,虽然:你仍然需要处理的空单的情况下,或许通过调用error与特定错误消息,像

mymaximum ListEnd = error " mymaximum: empty list is not allowed! "

暂无
暂无

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

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