用于Haskell id函数 [英] Uses for Haskell id function

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

问题描述

Haskell中 id函数的用途是什么?

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 :通过折叠建立一个功能:

Example 2: building up a function via a fold:

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

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

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

示例3 :函数的基本大小写为monoids(简体)。

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天全站免登陆