Haskell长度函数的实现 [英] Haskell Length function implementation

查看:94
本文介绍了Haskell长度函数的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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屋!

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