목록 모나드의 마법 :
ghci> let powers (a, b) = [a^n | n <- [0 .. b-1]]
ghci> powers (2, 3)
[1,2,4]
ghci> map powers [(2, 3), (5, 3)]
[[1,2,4],[1,5,25]]
ghci> sequence it
[[1,1],[1,5],[1,25],[2,1],[2,5],[2,25],[4,1],[4,5],[4,25]]
ghci> mapM powers [(2, 3), (5, 3)]
[[1,1],[1,5],[1,25],[2,1],[2,5],[2,25],[4,1],[4,5],[4,25]]
ghci> map product it
[1,5,25,2,10,50,4,20,100]
ghci> let allPowers list = map product $ mapM powers list
ghci> allPowers [(2, 3), (5, 3)]
[1,5,25,2,10,50,4,20,100]
이것은 아마도 조금 더 설명을 가치가있다.
당신은 당신의 자신의
cartesianProduct :: [[a]] -> [[a]]
cartesianProduct [] = [[]]
cartesianProduct (list:lists)
= [ (x:xs) | x <- list, xs <- cartesianProduct lists ]
등이 cartesianProduct [[1],[2,3],[4,5,6]]
⇒ [[1,2,4],[1,2,5],[1,2,6],[1,3,4],[1,3,5],[1,3,6]]
을 쓸 수 있었다.
그러나, comprehensions과 monads은 의도적으로 유사합니다. 표준 서곡은 sequence :: Monad m => [m a] -> m [a]
이고, m
이 목록 모나드 []
일 때 실제로 위에 서술 한 내용을 실제로 수행합니다.
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
은 sequence
및 map
의 단순한 구성입니다.
각 기본의 다양한 출력의 각 내부 목록에 단일 기본 숫자를 곱하고 싶습니다. 당신이 쓸 수 재귀
product list = product' 1 list
where product' accum [] = accum
product' accum (x:xs)
= let accum' = accum * x
in accum' `seq` product' accum' xs
또는 배
import Data.List
product list = foldl' (*) 1 list
실제로, product :: Num a => [a] -> a
가 이미 정의되어 사용! 나는이 언어를 좋아한다. ☺☺☺
'let powers (a, b) = [a^n | n <- [0 .. b-1]] ' – Tordek
@ Tordek 고마워, 원래 너무 빨리 건너 뜁니다. – ephemient
아름다운, 고마워. – ezpz