What are some interesting uses of higher-order functions?

后端 未结 14 579
走了就别回头了
走了就别回头了 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:38

    One interesting and slightly crazy thing you can do is simulate an object-oriented system using a function and storing data in the function's scope (i.e. in a closure). It's higher-order in the sense that the object generator function is a function which returns the object (another function).

    My Haskell is rather rusty so I can't easily give you a Haskell example, but here's a simplified Clojure example which hopefully conveys the concept:

    (defn make-object [initial-value]
      (let [data (atom {:value initial-value})]
          (fn [op & args]
            (case op 
              :set (swap! data assoc :value (first args))
              :get (:value @data)))))
    

    Usage:

    (def a (make-object 10))
    
    (a :get)
    => 10
    
    (a :set 40)
    
    (a :get)
    => 40
    

    Same principle would work in Haskell (except that you'd probably need to change the set operation to return a new function since Haskell is purely functional)

提交回复
热议问题