SlideShare a Scribd company logo
하스켈 프로그래밍
입문 4
하스켈 학교 2016년 6월 4일
서광열
Functor
class Functor f where
fmap :: (a -> b) -> f a -> f b
Functor의 한계
> fmap (+1) [1,2,3]
[2,3,4]
> fmap (+) [1,2,3] [4,5,6]
ERROR!
Applicative Functor
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
Functor vs Applicative
Functor
> fmap (+1) [1,2,3]
[2,3,4]
> pure (+) <*> [1,2,3] <*> [4,5,6]
[5,6,7,6,7,8,7,8,9]
Applicative Maybe 정의
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> x = fmap f x
Applicative Maybe 예제
> Just (+3) <*> Just 4
Just 7
> pure (+3) <*> Nothing
Nothing
> pure (+) <*> Just 3 <*> Just 4
Just 7
> (*) <$> Just 2 <*> Just 8
Just 16
Applicative []의 정의
instance Applicative [] where
pure x = [x]
fs <*> xs = [f x | f <- fs, x <- xs]
Applicative [] 예제
> (*) <$> [1,2,3] <*> [1,0,0,1]
[1,0,0,1,2,0,0,2,3,0,0,3]
> pure 7
7
> pure 7 :: [Int]
[7]
Applicative IO의 정의
instance Applicative IO where
pure = return
a <*> b = do f <- a
x <- b
return (f x)
Applicative IO 예제
main = do
a <- (++) <$> getLine <*> getLine
putStrLn a
liftA2
• 일반 함수를 두 개의 functor에 쉽게 apply 할 수 있게
해주는 함수
liftA2 :: (Applicative f) =>
(a -> b -> c) ->
f a -> f b -> f c
liftA2 f a b = f <$> a <*> b
liftA2 예제
> (+) <$> Just 3 <*> Just 4
Just 7
> liftA2 (+) (Just 3) (Just 4)
Just 7
Applicative Functor 법칙
1. pure f <*> x = fmap f x
2. pure id <*> v = v
3. pure (.) <*> u <*> v <*> w = u <*> (v <*> w)
4. pure f <*> pure x = pure (f x)
5. u <*> pure y = pure ($ y) <*> u
Foldable
• 리스트 foldr의 일반화
• foldr :: (a -> b -> b) -> b -> [a] -> b
mconcat
• foldr f z [a, b, c]
• a `f` (b `f` (c `f` z))
• f = (<>), z = mempty
• a <> (b <> (c <> mempty))
mconcat :: Monoid m => [m] -> m
mconcat = foldr mappend mempty
mconcat 예제
> mconcat ["Tree", "fingers"]
"Treefingers"
foldMap
• mconcat에서 Monoid 인스턴스 제약을 제거
foldMap :: Monoid m => (a -> m) -> [a] -> m
foldMap g = mconcat . fmap g
foldMap의 예제
> foldMap Sum [1..10]
Sum {getSum = 55}
foldr 다시 보기
• foldr :: (a -> (b -> b)) -> b -> [a] -> b
• b -> b는 composition에 대해 Monoid
• mappend = (.)
• mempty = id
newtype Endo b = Endo { appEndo :: b -> b }
instance Monoid Endo where
mempty = Endo id
Endo g `mappend` Endo f = Endo (g . f)
foldComposing
foldComposing :: (a -> (b -> b)) -> [a] -> Endo b
foldComposing f = foldMap (Endo . f)
foldr :: (a -> (b -> b)) -> b -> [a] -> b
foldr f z xs = appEndo (foldComposing f xs) z
• foldr을 foldMap을 이용해 정의할 수 있다는 의미
foldComposing 연산
1. foldComposing (+) [1, 2, 3]
2. foldMap (Endo . (+)) [1, 2, 3]
3. mconcat (fmap (Endo . (+)) [1, 2, 3])
4. mconcat (fmap Endo [(+1), (+2), (+3)])
5. mconcat [Endo (+1), Endo (+2), Endo (+3)]
6. Endo ((+1) . (+2) . (+3))
7. Endo (+6)
Foldable 타입 클래스
class Foldable t where
foldMap :: Monoid m => (a -> m) -> t a -> m
foldr :: (a -> b -> b) -> b -> t a -> b
• foldMap과 foldr 둘 중 하나만 정의하면 됨
Foldable 타입 클래스 함
수
• fold :: Monoid m => t m -> m --
generalised mconcat
• foldr' :: (a -> b -> b) -> b -> t a -
> b
• foldl :: (b -> a -> b) -> b -> t a -
> b
• foldl' :: (b -> a -> b) -> b -> t a -
> b
• foldr1 :: (a -> a -> a) -> t a -> a
• foldl1 :: (a -> a -> a) -> t a -> a
• toList :: t a -> [a]
• null :: t a -> Bool
• length :: t a -> Int
• elem :: Eq a => a -> t a -> Bool
• maximum :: Ord a => t a -> a
• minimum :: Ord a => t a -> a
• sum :: Num a => t a -> a
• product :: Num a => t a -> a
Data.Foldable 함수
• traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a ->
f ()
• Map each element of a structure to an action, evaluate
these actions from left to right, and ignore the results. For a
version that doesn't ignore the results see traverse.
• mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
• Map each element of a structure to a monadic action,
evaluate these actions from left to right, and ignore the
results. For a version that doesn't ignore the results see
mapM.
Foldable 예제
> import qualified Data.Map as M
> let testMap = M.fromList $ zip [0..] ["Yesterday","I","woke","up","sucking","a","lemon"]
> length testMap
7
> sum . fmap length $ testMap
29
> elem "lemon" testMap
True
> foldr1 (x y -> x ++ (' ' : y)) testMap
"Yesterday I woke up sucking a lemon"
Foldable 예제
> import Data.Foldable
> traverse_ putStrLn testMap
Yesterday
I
woke
up
sucking
a
lemon
Traversable
deleteIfNegative :: (Num a, Ord a) => a -> Maybe a
deleteIfNegative x = if x < 0 then Nothing else Just x
rejectWithNegatives :: (Num a, Ord a) => [a] -> Maybe [a]
• deleteIfNegative를 이용해서 rejectWithNegatives 를
구현하려면?
> let testList = [-5,3,2,-1,0]
> fmap deleteIfNegative testList
[Nothing,Just 3,Just 2,Nothing,Just 0]
No!!
Traversable 타입 클래
스
class (Functor t, Foldable t) => Traversable t where
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
sequenceA :: Applicative f => t (f a) -> f (t a)
-- These methods have default definitions.
-- They are merely specialised versions of the other two.
mapM :: Monad m => (a -> m b) -> t a -> m (t b)
sequence :: Monad m => t (m a) -> m (t a)
Traversable [] 정의
instance Traversable [] where
-- sequenceA :: Applicative f => [f a] -> f [a]
sequenceA [] = pure []
sequenceA (u:us) = (:) <$> u <*> sequenceA us
// or
instance Traversable [] where
sequenceA us =
foldr (u v -> (:) <$> u <*> v) (pure []) us
Foldable vs Traversable
• Foldable
• Monoid 콘텍스트
• fold
• foldMap
• Traversable
• Applicative 콘텍스트
• sequenceA
• traverse
Traversable 예제
> let rejectWithNegatives = sequenceA . fmap deleteIfNegative
> :t rejectWithNegatives
rejectWithNegatives
:: (Num a, Ord a, Traversable t) => t a -> Maybe (t a)
> rejectWithNegatives testList
Nothing
> rejectWithNegatives [0..10]
Just [0,1,2,3,4,5,6,7,8,9,10]
traverse를 이용한
Traversable [] 정의
instance Traversable [] where
traverse _ [] = pure []
traverse f (x:xs) = (:) <$> f x <*> traverse f xs
-- Or, equivalently:
instance Traversable [] where
traverse f xs =
foldr (x v -> (:) <$> f x <*> v) (pure []) xs
traverse와 sequenceA
traverse :: (Traversable t, Applicative f) => (a -> f
b) -> t a -> f (t b)
traverse f xs = sequenceA $ fmap f xs
sequenceA :: (Traversable t, Applicative f) => t (f
a) -> f (t a)
sequenceA xs = traverse id xs
Foldable/Traversable
출처: https://wiki.haskell.org/Foldable_and_Traversable
참고 자료
1. CS252 – Advanced Programming Language Principles
Applicative Functors
• http://cs.sjsu.edu/~austin/cs252-fall14/slides/CS252-
Day09-ApplicativeFunctors.pdf
2. Haskell/Foldable
• https://en.wikibooks.org/wiki/Haskell/Foldable
3. Haskell/Traversable
• https://en.wikibooks.org/wiki/Haskell/Traversable

More Related Content

What's hot

Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Codestasimus
 
Oh Composable World!
Oh Composable World!Oh Composable World!
Oh Composable World!
Brian Lonsdorf
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
Lawrence Evans
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
kenbot
 
Millionways
MillionwaysMillionways
Millionways
Brian Lonsdorf
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskell
Luca Molteni
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
gekiaruj
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
Namgee Lee
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
Karlijn Willems
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
Luka Jacobowitz
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
Luka Jacobowitz
 
Functional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianFunctional Patterns for the non-mathematician
Functional Patterns for the non-mathematician
Brian Lonsdorf
 

What's hot (13)

Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
 
Oh Composable World!
Oh Composable World!Oh Composable World!
Oh Composable World!
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 
Millionways
MillionwaysMillionways
Millionways
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskell
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 
Functional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianFunctional Patterns for the non-mathematician
Functional Patterns for the non-mathematician
 

Similar to 하스켈 프로그래밍 입문 4

Monads from Definition
Monads from DefinitionMonads from Definition
Monads from Definition
Dierk König
 
MP in Clojure
MP in ClojureMP in Clojure
MP in Clojure
Kent Ohashi
 
Practical cats
Practical catsPractical cats
Practical cats
Raymond Tay
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
Jongsoo Lee
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
Eric Torreborre
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
Hackraft
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
Eric Torreborre
 
Fp in scala with adts
Fp in scala with adtsFp in scala with adts
Fp in scala with adts
Hang Zhao
 
All You Need is Fold
All You Need is FoldAll You Need is Fold
All You Need is Fold
Mike Harris
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
Avjinder (Avi) Kaler
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
Avjinder (Avi) Kaler
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
Damian T. Gordon
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
rkaippully
 
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Dr. Volkan OBAN
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
Hang Zhao
 

Similar to 하스켈 프로그래밍 입문 4 (20)

Monads from Definition
Monads from DefinitionMonads from Definition
Monads from Definition
 
MP in Clojure
MP in ClojureMP in Clojure
MP in Clojure
 
Practical cats
Practical catsPractical cats
Practical cats
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Fp in scala with adts
Fp in scala with adtsFp in scala with adts
Fp in scala with adts
 
All You Need is Fold
All You Need is FoldAll You Need is Fold
All You Need is Fold
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
R code for data manipulation
R code for data manipulationR code for data manipulation
R code for data manipulation
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 

Recently uploaded

Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
Kamal Acharya
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 

Recently uploaded (20)

Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 

하스켈 프로그래밍 입문 4

  • 1. 하스켈 프로그래밍 입문 4 하스켈 학교 2016년 6월 4일 서광열
  • 2. Functor class Functor f where fmap :: (a -> b) -> f a -> f b
  • 3. Functor의 한계 > fmap (+1) [1,2,3] [2,3,4] > fmap (+) [1,2,3] [4,5,6] ERROR!
  • 4. Applicative Functor class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b
  • 5. Functor vs Applicative Functor > fmap (+1) [1,2,3] [2,3,4] > pure (+) <*> [1,2,3] <*> [4,5,6] [5,6,7,6,7,8,7,8,9]
  • 6. Applicative Maybe 정의 instance Applicative Maybe where pure = Just Nothing <*> _ = Nothing (Just f) <*> x = fmap f x
  • 7. Applicative Maybe 예제 > Just (+3) <*> Just 4 Just 7 > pure (+3) <*> Nothing Nothing > pure (+) <*> Just 3 <*> Just 4 Just 7 > (*) <$> Just 2 <*> Just 8 Just 16
  • 8. Applicative []의 정의 instance Applicative [] where pure x = [x] fs <*> xs = [f x | f <- fs, x <- xs]
  • 9. Applicative [] 예제 > (*) <$> [1,2,3] <*> [1,0,0,1] [1,0,0,1,2,0,0,2,3,0,0,3] > pure 7 7 > pure 7 :: [Int] [7]
  • 10. Applicative IO의 정의 instance Applicative IO where pure = return a <*> b = do f <- a x <- b return (f x)
  • 11. Applicative IO 예제 main = do a <- (++) <$> getLine <*> getLine putStrLn a
  • 12. liftA2 • 일반 함수를 두 개의 functor에 쉽게 apply 할 수 있게 해주는 함수 liftA2 :: (Applicative f) => (a -> b -> c) -> f a -> f b -> f c liftA2 f a b = f <$> a <*> b
  • 13. liftA2 예제 > (+) <$> Just 3 <*> Just 4 Just 7 > liftA2 (+) (Just 3) (Just 4) Just 7
  • 14. Applicative Functor 법칙 1. pure f <*> x = fmap f x 2. pure id <*> v = v 3. pure (.) <*> u <*> v <*> w = u <*> (v <*> w) 4. pure f <*> pure x = pure (f x) 5. u <*> pure y = pure ($ y) <*> u
  • 15. Foldable • 리스트 foldr의 일반화 • foldr :: (a -> b -> b) -> b -> [a] -> b
  • 16. mconcat • foldr f z [a, b, c] • a `f` (b `f` (c `f` z)) • f = (<>), z = mempty • a <> (b <> (c <> mempty)) mconcat :: Monoid m => [m] -> m mconcat = foldr mappend mempty
  • 17. mconcat 예제 > mconcat ["Tree", "fingers"] "Treefingers"
  • 18. foldMap • mconcat에서 Monoid 인스턴스 제약을 제거 foldMap :: Monoid m => (a -> m) -> [a] -> m foldMap g = mconcat . fmap g
  • 19. foldMap의 예제 > foldMap Sum [1..10] Sum {getSum = 55}
  • 20. foldr 다시 보기 • foldr :: (a -> (b -> b)) -> b -> [a] -> b • b -> b는 composition에 대해 Monoid • mappend = (.) • mempty = id newtype Endo b = Endo { appEndo :: b -> b } instance Monoid Endo where mempty = Endo id Endo g `mappend` Endo f = Endo (g . f)
  • 21. foldComposing foldComposing :: (a -> (b -> b)) -> [a] -> Endo b foldComposing f = foldMap (Endo . f) foldr :: (a -> (b -> b)) -> b -> [a] -> b foldr f z xs = appEndo (foldComposing f xs) z • foldr을 foldMap을 이용해 정의할 수 있다는 의미
  • 22. foldComposing 연산 1. foldComposing (+) [1, 2, 3] 2. foldMap (Endo . (+)) [1, 2, 3] 3. mconcat (fmap (Endo . (+)) [1, 2, 3]) 4. mconcat (fmap Endo [(+1), (+2), (+3)]) 5. mconcat [Endo (+1), Endo (+2), Endo (+3)] 6. Endo ((+1) . (+2) . (+3)) 7. Endo (+6)
  • 23. Foldable 타입 클래스 class Foldable t where foldMap :: Monoid m => (a -> m) -> t a -> m foldr :: (a -> b -> b) -> b -> t a -> b • foldMap과 foldr 둘 중 하나만 정의하면 됨
  • 24. Foldable 타입 클래스 함 수 • fold :: Monoid m => t m -> m -- generalised mconcat • foldr' :: (a -> b -> b) -> b -> t a - > b • foldl :: (b -> a -> b) -> b -> t a - > b • foldl' :: (b -> a -> b) -> b -> t a - > b • foldr1 :: (a -> a -> a) -> t a -> a • foldl1 :: (a -> a -> a) -> t a -> a • toList :: t a -> [a] • null :: t a -> Bool • length :: t a -> Int • elem :: Eq a => a -> t a -> Bool • maximum :: Ord a => t a -> a • minimum :: Ord a => t a -> a • sum :: Num a => t a -> a • product :: Num a => t a -> a
  • 25. Data.Foldable 함수 • traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () • Map each element of a structure to an action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see traverse. • mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m () • Map each element of a structure to a monadic action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see mapM.
  • 26. Foldable 예제 > import qualified Data.Map as M > let testMap = M.fromList $ zip [0..] ["Yesterday","I","woke","up","sucking","a","lemon"] > length testMap 7 > sum . fmap length $ testMap 29 > elem "lemon" testMap True > foldr1 (x y -> x ++ (' ' : y)) testMap "Yesterday I woke up sucking a lemon"
  • 27. Foldable 예제 > import Data.Foldable > traverse_ putStrLn testMap Yesterday I woke up sucking a lemon
  • 28. Traversable deleteIfNegative :: (Num a, Ord a) => a -> Maybe a deleteIfNegative x = if x < 0 then Nothing else Just x rejectWithNegatives :: (Num a, Ord a) => [a] -> Maybe [a] • deleteIfNegative를 이용해서 rejectWithNegatives 를 구현하려면? > let testList = [-5,3,2,-1,0] > fmap deleteIfNegative testList [Nothing,Just 3,Just 2,Nothing,Just 0] No!!
  • 29. Traversable 타입 클래 스 class (Functor t, Foldable t) => Traversable t where traverse :: Applicative f => (a -> f b) -> t a -> f (t b) sequenceA :: Applicative f => t (f a) -> f (t a) -- These methods have default definitions. -- They are merely specialised versions of the other two. mapM :: Monad m => (a -> m b) -> t a -> m (t b) sequence :: Monad m => t (m a) -> m (t a)
  • 30. Traversable [] 정의 instance Traversable [] where -- sequenceA :: Applicative f => [f a] -> f [a] sequenceA [] = pure [] sequenceA (u:us) = (:) <$> u <*> sequenceA us // or instance Traversable [] where sequenceA us = foldr (u v -> (:) <$> u <*> v) (pure []) us
  • 31. Foldable vs Traversable • Foldable • Monoid 콘텍스트 • fold • foldMap • Traversable • Applicative 콘텍스트 • sequenceA • traverse
  • 32. Traversable 예제 > let rejectWithNegatives = sequenceA . fmap deleteIfNegative > :t rejectWithNegatives rejectWithNegatives :: (Num a, Ord a, Traversable t) => t a -> Maybe (t a) > rejectWithNegatives testList Nothing > rejectWithNegatives [0..10] Just [0,1,2,3,4,5,6,7,8,9,10]
  • 33. traverse를 이용한 Traversable [] 정의 instance Traversable [] where traverse _ [] = pure [] traverse f (x:xs) = (:) <$> f x <*> traverse f xs -- Or, equivalently: instance Traversable [] where traverse f xs = foldr (x v -> (:) <$> f x <*> v) (pure []) xs
  • 34. traverse와 sequenceA traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) traverse f xs = sequenceA $ fmap f xs sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a) sequenceA xs = traverse id xs
  • 36. 참고 자료 1. CS252 – Advanced Programming Language Principles Applicative Functors • http://cs.sjsu.edu/~austin/cs252-fall14/slides/CS252- Day09-ApplicativeFunctors.pdf 2. Haskell/Foldable • https://en.wikibooks.org/wiki/Haskell/Foldable 3. Haskell/Traversable • https://en.wikibooks.org/wiki/Haskell/Traversable