我有 2 個不同的非常簡單的函式,它們具有相同的輸入輸出結構(當 3 個音符的平均值 >= 4(函式1)時,它們都回傳一個計數(*),而當 3 個音符的平均值小于 4 時,另一個回傳一個計數(*) ( function2 )),它們都可以單獨正常作業,但現在我需要將兩者都加入一個具有 2 個輸出的函式中,我現在可能是一個非常簡單的問題,但我才剛剛開始使用 Haskell:
function1::[(String, Int,Int,Int)]->Int
function1 ((name,note1,note2,note3):xs) =
if (note1 note2 note3) `div` 3 >=4 then length xs else length xs
function2::[(String, Int,Int,Int)]->Int
function2 ((name,note1,note2,note3):xs) =
if (note1 note2 note3) `div` 3 <4 then length xs else length xs
謝謝!
uj5u.com熱心網友回復:
您可以使用 Control.Arrow 中的 &&&。
combineFunctions f1 f2 = f1 &&& f2
然后像這樣使用它:
combinedFunc = combineFunctions function1 function2
(res1,res2) = combinedFunc sharedArg
uj5u.com熱心網友回復:
您已經(name,note1,note2,note3)在輸入資料中使用了元組,因此您必須熟悉這個概念。
同時產生兩個輸出的最簡單方法是將兩者放入一個元組中:
combinedFunction f1 f2 input = (out1, out2)
where
out1 = f1 input
out2 = f2 input
碰巧這可以寫成更短的combinedFunction f1 f2 = f1 &&& f2甚至combinedFunction = (&&&),但現在這不太重要。
同時產生兩個輸出的更有趣的方法是重新定義產生輸出的含義:
combinedFunWith k f1 f2 input = k out1 out2
where
out1 = f1 input
out2 = f2 input
在這里,我們不只是在元組中回傳它們,而是將它們作為引數傳遞給其他用戶指定的函式k。讓它決定如何處理兩個輸出做!
也很容易看出,我們的第一個版本可以用第二個 as 表示 combinedFunction = combinedFunWith (,),因此第二個版本似乎更通用((,)只是撰寫函式的一種更短的方式foo x y = (x,y),沒有給它命名)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338422.html
