Haskell write your version of a ($) function

拈花ヽ惹草 提交于 2019-12-23 06:22:35

问题


Could someone help me with writing my own version of the ($) function? This is my attempt which does not work.

f function (x:xs) = f (x:xs)

回答1:


First, why do you think you need : or foldr here? These are exclusive to lists. $ has nothing to do with lists.

f function (x) = f (x) is more like it, however it seems you're confused about whether you defining function with f as an argument, or vice versa. In fact, f function (x) = f (x) means this:

f = \function x -> f x

i.e. you're defining f as a function which takes an argument called function (that is never actually used) and another argument x to which it then applies the very function you're defining right here... this kind of recursive knot-tying is actually possible in Haskell (and sometimes quite useful), but in this case it doesn't make any sense.

What you actually want to write is much simpler:

f $ x = f x

note that $, because it consists of a non-letter symbol, is an infix and therefore parsed differently:

($) = \f x -> f x

Which means, $ takes a function and an argument and applies the function to the argument; that's it.

You could also achieve this with a name with letters by using backticks to have it parsed as an infix:

f `function` x = f x

...or simply

function f x = f x



回答2:


% ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> :i ($)
($) :: (a -> b) -> a -> b       -- Defined in ‘GHC.Base’
infixr 0 $

So lets just copy and paste, defining our own $$ (borrowing the logic from the discussion already presented by @leftaroundabout):

($$) :: (a -> b) -> a -> b
f $$ x = f x
infixr 0 $$


来源:https://stackoverflow.com/questions/37623871/haskell-write-your-version-of-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!