问题描述
code>但我甚至不确定语法。例如,为什么我不能用可折叠a ?
$ b替换 ta $ b还有,奖金问题,如果我必须自己定义 foldl ,我会从基本案例开始
foldl fb [] = []
基本情况需要一个列表,比接受 Foldable 没有多大意义。什么是我可以用作基本案例的空可折叠?
code>被称为类型类。说可折叠t => 声明 t 必须实现 Foldable 。但是, t 仍然是 t ,并且不会折叠为对可折叠界面就像在Java中一样。这就是为什么你不能只有可折叠a 。
绝对检查,了解 Foldable 的要求以及可以获取您的方法。
无论如何,如果你想使用 Foldable 的方法之一,那么可以使用已知的 Foldable 类型,比如 Set :
将限定数据集导入为S
导入Data.Foldable
sumSet ::(Num n)=> S.Set n - > n
sumSet ns = foldl'(\ n acc - > n + acc)0 ns - 如果您想要
或者您可以使用一个类型参数并将其限制为可折叠:
sumFld ::(Num n,Foldable f)=> f n - > n - 不同签名
sumFld ns = foldl'(\ n acc - > n + acc)0 ns - 同一个实现!
以下打印6次,两次:
main :: IO()
main = print(sumSet $ S.fromList [1,2,3])>> print(sumFld $ S.fromList [1,2,3])
When I ask about the foldl type, what I see is this:
*Main> :t foldl foldl :: Foldable t => (b -> a -> b) -> b -> t a -> bIn this case, what is t a?
I guess it means that the function is using a Foldable parametrized with a but I'm not even really sure about the syntax. For instance, why can't I substitute t a with Foldable a?
And, bonus question, if I had to define foldl myself, I would start with the base case
foldl f b [] = []But if the base case takes a list, than it would not make much sense to accept a Foldable. What is the "empty Foldable" that I could use as the base case?
解决方案Foldable is something called a "typeclass". Saying Foldable t => declares that t must implement the requirements of Foldable. However, t remains t, and doesn't get collapsed into a reference to a Foldable interface like it might in Java. That's why you can't just have Foldable a.
Definitely check out https://hackage.haskell.org/package/base-4.10.1.0/docs/Data-Foldable.html for an explanation of the requirements of Foldable and what methods that gets you.
Anyways, if you want to use one of Foldable's methods, then either use a known Foldable type like Set:
import qualified Data.Set as S import Data.Foldable sumSet :: (Num n) => S.Set n -> n sumSet ns = foldl' (\ n acc -> n + acc ) 0 ns --make this pointfree if you wantOr you can take a type parameter and constrain it to be foldable:
sumFld :: (Num n, Foldable f) => f n -> n --different signature sumFld ns = foldl' (\ n acc -> n + acc ) 0 ns --same implementation!The following prints 6, twice:
main :: IO () main = print (sumSet $ S.fromList [1, 2, 3]) >> print (sumFld $ S.fromList [1, 2, 3])
这篇关于我不确定我是否理解haskell中foldl函数的类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!