我真的希望我沒有在這里走入死胡同。我有一個行為,它給出當前選定的顏色和當前滑鼠坐標,然后在單擊滑鼠時執行任務。該任務涉及查看一個串列,然后更新該串列中的值,以便稍后檢索它。我可以“存盤”所選顏色的事實讓我希望可以以類似的方式存盤串列。我只是在死胡同,不知道如何解決這個問題。非常感謝一些幫助。
-- There is a Blue button and a Red button on our UI. Whichever
-- button was clicked last is our current color selection.
colorRedSelected = const ColorRed <$ UI.click redButton
colorBlueSelected = const ColorBlue <$ UI.click blueButton
-- we combine both the above Events to create a new one that tells us the current selected color
colorSelected = unionWith const colorRedSelected colorBlueSelected
-- accumulate values for our Behaviour, starting with ColorRed selected by default
colorMode <- accumB ColorRed modeEvent
-- create a Behaviour
mouseCoordinate <- stepper (0,0) $ UI.mousemove canvas
-- want to start with the list [1,2,3,4], but this value should change later.
-- I have 'never' here, as I don't know what else to put here yet.
listState <- accumB ([1,2,3,4]) never
-- Combine the Behaviours, we now have a tuple (chosenColorMode, mouseCoordinateTuple, savedList)
let choices = (,,) <$> colorMode <*> mouseCoordinate <*> listState
-- Apply the event (of the user clicking the canvas) to the Behaviour,
-- creating a new Event that returns the above tuple when it fires
makeChoice = choices <@ UI.click canvas
onEvent makeChoice $ \(colorMode, (x,y), savedList) -> do
...
-- in this block we use the savedList, and generate a newList.
-- I want to update the choicePosition behaviour so that the newList
-- replaces the old savedList.
uj5u.com熱心網友回復:
完全歸功于duplode 的回復,我將介紹它是如何解決的:
假設我們有一個函式可以根據某個值以某種方式修改串列。如何/為什么updateMyList修改串列對于這個解釋并不重要,我們只需要知道它的型別。對于這個例子,我們會說決定串列如何變化的值是一個滑鼠坐標元組 (x, y),我們將把它作為它的第一個引數傳遞:
updateMyList :: (Double, Double) -> [Integer] -> [Integer]
updateMyList (x, y) oldList = ...
如果我們有一個事件告訴我們用戶點擊時的滑鼠坐標:
mouseCoords :: Behavior (Double, Double)
mouseCoords <- stepper (0,0) $ UI.mousemove canvas
mouseClicked :: Event (Double, Double)
mouseClicked = mouseCoords <@ UI.click canvas -- this is the Event we need
我們需要做的是fmap串列更新功能到mouseClicked:
listChangeEvent = fmap updateMyList mouseClicked
所以我們創建了一個新事件:當mouseClicked被觸發時,滑鼠坐標作為第一個引數傳遞給,updateMyList這就是我們的新事件在那個時間戳的值。但這是一個部分應用的函式,updateMyList仍然需要一個[Integer]作為引數,因此,listChangeEvent具有以下型別:
listChangeEvent :: Event ([Integer] -> [Integer])
現在,這是聰明的部分:如果我們使用accumB并指定起始累加器(即我們的起始串列,[1,2,3,4]),然后也使用上面listChangeEvent的作為 EventaccumB從以下位置獲取其值:
listState <- accumB ([1,2,3,4]) listChangeEvent
然后那個累加器將被傳遞給Event ([Integer] -> [Integer]). 這意味著第一次listChangeEvent觸發器updateMyList將被呼叫:
updateMyList (x, y) [1,2,3,4] -- (x, y) being the mouse coordinates at that time
其結果將成為 中的新累加器值listState,并且該新串列將用作updateMyList下次listChangeEvent觸發器的引數,依此類推。
我們可以將它用于任何事情,它不一定是我們正在修改的串列。這只是為我們提供了一種使用值初始化 Behavior 的方法,并且我們可以通過創建等效于 的函式來準確指定 Behavior 的下一個值是如何派生的updateMyList。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/416359.html
標籤:
