2

I have this function:

myF :: String -> String
myF arg1 = "const" ++ arg1

Is there any way to simplify it? I think it might have to do with the operator "." but I can't figure out how to apply it here.

0

1 Answer 1

11

The magic of currying:

myF :: String -> String
myF = (++) "const"

or (as mentioned by @jamshidh)

myF :: String -> String
myF = ("const" ++)

Explanation

We say (++) is a function takes two arguments but really all functions in Haskell take only one argument. Lets look at the signature for the (++) function:

(++) :: String -> String -> String

We can describe (++) or "the concatenation" function as acting like so:

"Take one string and return a function that takes another string concatenates (joins together) the two strings and return that string"

So when we say myF = (++) "const" we are assigning the resulting function from applying the first string to (++) function to myF function. This is known as "Partial Application".

Notice we don't need to include an argument at the end of function like this but this is still perfectly fine:

myF arg = "const" ++ arg

We can leave out the "arg" because from the partially applied "concat" function we already know that we are expecting one more string argument.

Sign up to request clarification or add additional context in comments.

2 Comments

And of course, you can always use directly on code as ("const" ++)
@jamshidh of course! added it to the answer, thanks mate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.