by Kiro · 10y ago · 0 comments
> The type annotation for connectWords is telling us that connectWords is a function that accepts two strings and returns a string.
Or maybe I misunderstand this whole thing. I know nothing about Haskell/Elm.
f: Int -> Int -> Int
f a b = a + b
the compiler (at least in Haskell) creates f as a function that takes a single argument, a, and outputs a function. That outputted function takes a single argument, b and outputs an Int.When you apply the function f:
f 5 7
what's really happening here is that f is first applied to 5. This creates a new function, call it g, taking in a single integer and outputting that integer plus 5. Then, this new function is applied to 7. (The compiler may optimize a lot of this away, but that is how you should think of what's happening in my opinion.)Hope that helps!
f: Int -> (Int -> Int)
...
(f 5) 7So in order to construct functions that accept more than one argument, you actually return successive functions that apply successive arguments, known as currying.
Does this kind of 1/arity have performance implications for Haskell? Does the compiler lower (or is it rise? inline?) the functions to produce efficient machine code?
connectWords : String -> String -> String
connectWords firstWord secondWord =
firstWord ++ secondWord let prefix = connectWords "Hello "
world = prefix "world"
bob = prefix "bob"
in ...
`world` is "Hello world", and `bob` is "Hello bob". That is the power of currying. A maybe more useful example is specifying the mapping function in `List.map` without supplying the list to map over. This allows you to use the same map with multiple lists. connectWords = \ firstWord -> \ secondWord -> firstWord ++ secondWord