Haskell长度函数的实现 [英] Haskell Length function implementation
问题描述
myLength :: [a] - >整数
myLength = foldr(\ x - >(+)1)0
myLength1 :: [a] - >整数
myLength1 [] = 0
myLength1(x:xs)=(+1)(myLength1 xs)
以上是2个长度函数。我的问题是哪一个更好?
从我自己的角度来看, myLength1 更好理解,
对于操作列表来说看起来很自然。
<但是 myLength 看起来更短并且不使用递归,这是否意味着 myLength
比 myLength1 $ b的运行速度快$ b
请记住 foldr
的这个伪执行:
foldr :: function - >初始值设定项 - > [a] - > b
foldr _ i [] = i
foldr fi(x:xs)= x`f`(foldr x xs)
现在我们有您的代码
myLength :: [a] - >整数
myLength = foldr(\ x - >(+)1)0
myLength1 :: [a] - >整数
myLength1 [] = 0
myLength1(x:xs)=(+1)(myLength1 xs)
因为 foldr
本身也是递归的,所以myLength1和myLength将几乎相同,但在第一种情况下,递归调用由foldr完成明确地由你自己。他们应该在同一时间运行。
I am start learning Haskell programming, and try to understand list struct, hence wrote list length function.
myLength :: [a] -> Integer
myLength = foldr (\x -> (+) 1) 0
myLength1 :: [a] -> Integer
myLength1 [] = 0
myLength1 (x:xs) = (+1) (myLength1 xs)
Above are 2 length functions. my question is which one is better? from my own point of view, myLength1 is much more better to understand, and looks natural for operating list.
But myLength looks shorter and not use recursion, does that imply myLength run fast than myLength1
Take in mind this "pseudo implementation" of foldr
:
foldr :: function -> initializer -> [a] -> b
foldr _ i [] = i
foldr f i (x:xs) = x `f` (foldr f i xs)
Now we have your code
myLength :: [a] -> Integer
myLength = foldr (\x -> (+) 1) 0
myLength1 :: [a] -> Integer
myLength1 [] = 0
myLength1 (x:xs) = (+1) (myLength1 xs)
Since foldr
is also recursive itself, your myLength1 and myLength will be almost the same but in the first case the recursive call is done by foldr instead of explicitly by yourself. They should run around the same time.
这篇关于Haskell长度函数的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!