Haskell id 函数的用途 [英] Uses for Haskell id function

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

问题描述

id 函数在 Haskell 中有哪些用途?>

Which are the uses for id function in Haskell?

推荐答案

作为 的参数很有用高阶函数(将函数作为参数的函数),您希望某些特定值保持不变.

It's useful as an argument to higher order functions (functions which take functions as arguments), where you want some particular value left unchanged.

示例 1:如果值在 Just 中,则保留它,否则返回默认值 7.

Example 1: Leave a value alone if it is in a Just, otherwise, return a default of 7.

Prelude Data.Maybe> :t maybe
maybe :: b -> (a -> b) -> Maybe a -> b

Prelude Data.Maybe> maybe 7 id (Just 2)
2

示例 2:通过折叠构建函数:

Prelude Data.Maybe> :t foldr (.) id [(+2), (*7)]
:: (Num a) => a -> a

Prelude Data.Maybe> let f = foldr (.) id [(+2), (*7)]

Prelude Data.Maybe> f 7
51

我们使用 id 作为基本情况,通过将函数列表与 (.) 折叠在一起,构建了一个新函数 f.

We built a new function f by folding a list of functions together with (.), using id as the base case.

示例 3:作为幺半群的函数的基本情况(简化).

Example 3: the base case for functions as monoids (simplified).

instance Monoid (a -> a) where
        mempty        = id
        f `mappend` g = (f . g)

类似于我们的 fold 示例,函数可以被视为可连接的值,id 用于空情况,(.) 作为附加.

Similar to our example with fold, functions can be treated as concatenable values, with id serving for the empty case, and (.) as append.

示例 4:一个简单的哈希函数.

Example 4: a trivial hash function.

Data.HashTable> h <- new (==) id :: IO (HashTable Data.Int.Int32 Int)

Data.HashTable> insert h 7 2

Data.HashTable> Data.HashTable.lookup h 7
Just 2

哈希表需要哈希函数.但是如果你的密钥已经被散列了怎么办?然后传递 id 函数,填充为您的哈希方法,性能开销为零.

Hashtables require a hashing function. But what if your key is already hashed? Then pass the id function, to fill in as your hashing method, with zero performance overhead.

这篇关于Haskell id 函数的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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