What are some interesting uses of higher-order functions?

后端 未结 14 586
走了就别回头了
走了就别回头了 2021-01-30 00:55

I\'m currently doing a Functional Programming course and I\'m quite amused by the concept of higher-order functions and functions as first class citizens. However, I can\'t yet

14条回答
  •  花落未央
    2021-01-30 01:52

    Here's a small paraphrased code snippet:

    rays :: ChessPieceType -> [[(Int, Int)]]
    rays Bishop = do
      dx <- [1, -1]
      dy <- [1, -1]
      return $ iterate (addPos (dx, dy)) (dx, dy)
    ...  -- Other piece types
    
    -- takeUntilIncluding is an inclusive version of takeUntil
    takeUntilIncluding :: (a -> Bool) -> [a] -> [a]
    
    possibleMoves board piece = do
      relRay <- rays (pieceType piece)
      let ray = map (addPos src) relRay
      takeUntilIncluding (not . isNothing . pieceAt board)
        (takeWhile notBlocked ray)
      where
        notBlocked pos =
          inBoard pos &&
          all isOtherSide (pieceAt board pos)
        isOtherSide = (/= pieceSide piece) . pieceSide
    

    This uses several "higher order" functions:

    iterate :: (a -> a) -> a -> [a]
    takeUntilIncluding  -- not a standard function
    takeWhile :: (a -> Bool) -> [a] -> [a]
    all :: (a -> Bool) -> [a] -> Bool
    map :: (a -> b) -> [a] -> [b]
    (.) :: (b -> c) -> (a -> b) -> a -> c
    (>>=) :: Monad m => m a -> (a -> m b) -> m b
    

    (.) is the . operator, and (>>=) is the do-notation "line break operator".

    When programming in Haskell you just use them. Where you don't have the higher order functions is when you realize just how incredibly useful they were.

提交回复
热议问题