Haskell function application and currying

后端 未结 3 655
南方客
南方客 2021-01-30 08:22

I am always interested in learning new languages, a fact that keeps me on my toes and makes me (I believe) a better programmer. My attempts at conquering Haskell come and go - t

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 09:03

    I'd like to add my two cents. The question and answer make it sound like . is some magical operator that does strange things with re-arranging function calls. That's not the case. . is just function composition. Here's an implementation in Python:

    def dot(f, g):
        def result(arg):
            return f(g(arg))
        return result
    

    It just creates a new function which applies g to an argument, applies f to the result, and returns the result of applying f.

    So (concatMap . ins) 1 [[2, 3]] is saying: create a function, concatMap . ins, and apply it to the arguments 1 and [[2, 3]]. When you do concatMap (ins 1 [[2,3]]) you're instead saying, apply the function concatMap to the result of applying ins to 1 and [[2, 3]] - completely different, as you figured out by Haskell's horrendous error message.

    UPDATE: To stress this even further. You said that (f . g) x was another syntax for f (g x). This is wrong! . is just a function, as functions can have non-alpha-numeric names (>><, .., etc., could also be function names).

提交回复
热议问题