我必須實作一個(n)[a -> b] -> [a] -> [b]函式,該函式必須在第二個串列的相應元素上運行給定的函式。例如:
functionList [\x->x 2] [2] == [4]
functionList [\x->x 2, \x->x-2, \x->x*2] [2,3,6] == [4,1,12]
到目前為止,我有這個:
functionList f xs = [ f x | x <- f ]
它回傳一個型別匹配錯誤,我不知道該怎么辦。
uj5u.com熱心網友回復:
您可以使用zip :: [a] -> [b] -> [(a,b)]來簡化問題。如果您想直接使用它,可能看起來像a = (map (uncurry ($))) . zip,但這zipWith是您應該使用的普通快捷方式。
另一種選擇是使用ZipList( docs )。
import Control.Applicative (ZipList(..))
-- I'm just writing this in the text box; i haven't checked if it parses.
a fs xs = getZipList $ ($) <$> (ZipList fs) <*> (ZipList xs)
ZipList 對于這種非常簡單的情況,可能是最糟糕(最冗長,沒有清晰優勢)的解決方案。
當然,您也可以通過對串列結構進行模式匹配來重新實作 zip。我不希望這有任何好處,但是如果zip您是新手,那么您應該花一點時間寫出兩個版本,僅供練習/理解。
a [] _ = []
a _ [] = []
a (f:fs) (x:xs) = ...
uj5u.com熱心網友回復:
比@ShapeOfMatter 的優秀答案略有改進的是:
import Control.Applicative (ZipList(..))
a :: [a -> b] -> [a] -> [b]
a fs xs = getZipList (ZipList fs <*> ZipList xs)
uj5u.com熱心網友回復:
您可以使用并行串列推導式:
{-# LANGUAGE ParallelListComp #-}
functionList fs xs = [f x | f <- fs | x <- xs]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/374156.html
