gpt4 book ai didi

javascript - 生成唯一 ID 的纯函数式方法

转载 作者:行者123 更新时间:2023-11-29 17:54:38 24 4
gpt4 key购买 nike

这更像是一个理论问题,但我觉得一定有办法做到这一点。

我有 JS 组件,在创建它们时,它们需要为 html 元素分配一个唯一的 id,该元素尚未在任何其他组件中使用过。这通常是非常微不足道的:

let currentId = 0;
function getNextId() {
currentId += 1;
return currentId;
}

function MyComponent() {
this.id = getNextId();

// Code which uses id
}

let c1 = new MyComponent();
// c1.id === 1
let c2 = new MyComponent();
// c2.id === 2

我想知道是否有任何方法可以只使用纯函数来做这种事情,因为我正在努力思考一些更高级的纯函数思想。据我所知,它需要 Monad 或类似的东西才能完成,但我不知道该怎么做。

谢谢!

最佳答案

在 Haskell 中,你可以这样写

import Control.Monad.State

data Component = Component Int String deriving (Show)

getNextId :: State Int Int
getNextId = do x <- get
put (x + 1)
return x

makeComponent :: String -> State Int Component
makeComponent name = do x <- getNextId
return (Component x name)

components = evalState (traverse makeComponent ["alice", "bob"]) 0

main = print $ components

上面的脚本会输出

[Component 0 "alice",Component 1 "bob"]

因为每次“调用”getNextId 都会“返回”行中的下一个数字。 traverse 函数类似于 map,但它确保每个 monad 的效果在将 makeComponent 应用于每个值的过程中发生。

This link可能会提供一些帮助使其适应 Javascript。


State 类型的构造函数本身只是一个函数的包装器,此处的类型为 Int -> (Int, Int)。此类型的 Monad 实例可让您避免编写如下所示的代码:

getNextID :: Int -> (Int, Int)
getNextID x = (x, x+1)

makeComponent :: String -> Int -> (Int, Int)
makeComponent name x = let (now, then) = getNextID x
in (then, Component now name)

components = let state_0 = 0
(state_1, c1) = makeComponent "alice" state_0
(state_2, c2) = makeComponent "bob" state_1
in [c1, c2]

关于javascript - 生成唯一 ID 的纯函数式方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40426446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com