[英]Haskell - Join two functions with the same input
我有 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
謝謝!
您可以使用 Control.Arrow 中的 &&&。
combineFunctions f1 f2 = f1 &&& f2
然后像這樣使用它:
combinedFunc = combineFunctions function1 function2
(res1,res2) = combinedFunc sharedArg
您已經在輸入數據中使用了元組,因此您必須熟悉這個概念。
同時產生兩個輸出的最簡單方法是將兩者放入一個元組中:
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
。 讓它決定如何處理做輸出!
也很容易看出,我們的第一個版本可以用第二個表示,如combinedFunction = combinedFunWith (,)
,所以第二個版本似乎更通用( (,)
只是編寫函數foo xy = (x,y)
一種更短的方式foo xy = (x,y)
,沒有給它一個名字)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.