【发布时间】:2017-12-05 18:38:00
【问题描述】:
我是 haskell 的新手,我读过一些关于这个叫做类型签名的东西,但是有一些东西我不明白。
这是我正在查看的代码:
--mult applies product
mult :: Num a => [a] -> a
mult = foldr (*) 1
--posList filters positive numbers out
posList :: (Ord a, Num a) => [a] -> [a]
posList = filter (>0)
--trueList determines whether all of the members of a list are T or not
trueList :: [Bool] -> Bool
trueList = foldr(&&) True
--evenList determines where all of the members of a list are even or not
evenList :: (Integral a, Foldable t) => t a -> Bool
evenList x = if (((foldr (+) 2 x ) `mod` 2) == 0) then True else False
所以,我知道你可以用不同的方式更轻松地完成这些功能,但我被分配使用更高阶的功能 map、filter 和 foldr,所以我不得不这样做。无论如何,我了解这些功能是如何工作的,因为我是编写它们的人,我不明白这些术语Integral,Foldable,它们是什么意思?以及它们在 Haskell 中的名称是什么?
【问题讨论】:
-
你测试
evenList了吗?我建议你试试evenList [1,3]。 -
Integral 和 Foldable 是 type classes,google 这个词。基本上
Foldable t的意思是“t 是一个类似列表的类型”。 -
类型类是 Haskell 中的重载方式。一个类型通过实现一些函数来实现一个类型类。例如,
(+)的类型是Num a => a -> a -> a,所以如果我定义了一个我希望能够添加的类型Foo,那么我需要定义(+) :: Foo -> Foo -> Foo,我只能通过实例化Num类来实现Foo -
@chi ahahahha 感谢提醒我修复了 evenList :: [Int] -> Bool evenList xs = foldr (&&) (True) (map (even) xs)
-
@MostafaIbrahim 好多了 ;-)