Currying 3 Arguments in Haskell

前端 未结 3 701
说谎
说谎 2020-11-28 12:35

I\'m having trouble with currying a function to remove three arguments in Haskell.

Disclaimer: Not Coursework, I was asked this question by someone struggling with

3条回答
  •  孤街浪徒
    2020-11-28 12:49

    The key observation for me is that infix operators can be written prefix:

    funcB as = (!!) . (iterate . funcA) as
    funcB as = (.) (!!) ((iterate . funcA) as)
    

    Once you've gotten here, you have half a chance of recognizing that this is a composition, with (.) (!!) as the first argument and iterate . funcA as the second argument:

    funcB as = (  ((.) (!!)) . (iterate . funcA)  ) as
    

    Now it's clear how to simplify this; after that, there's a lot of aesthetic choices about how to write it. For example, we might observe that (.) is associative, and so we can drop some parentheses; likewise, we can use operator sections to merge the unsightly ((.) (!!)) if you think it's more readable that way.

    funcB = (  ((.) (!!)) . (iterate . funcA)  )
    funcB = (.) (!!) . iterate . funcA -- uncontroversial parenthesis removal
    funcB = ((!!) .) . iterate . funcA -- possibly controversial section rewrite
    

    By the way, I don't think the beginning of your derivation is correct. You reached the right conclusion, but via incorrect middle steps. Corrected, it should look like this:

    funcB as str n = iterate (funcA as) str !! n
    funcB as str n = (!!) (iterate (funcA as) str) n
    funcB as str = (!!) (iterate (funcA as) str)
    funcB as = (!!) . iterate (funcA as)
    

提交回复
热议问题