I’m new to haskell and I’m trying to make a function that will multiply an int by every element of a list.
Example:
mult 2 [2,4,6]
Returns:
[4,8,12]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Break the problem down into conceptual steps:
You want to do something to every element of a list, which is a general operation provided by the
mapfunction. Using that, you can ignore the list, and consider only what you need to do with a single element.You want to multiply two numbers together. In any single use of the function, one of those numbers will be constant, so we can give it a name as an argument to the function:
mult x = .... Now we can treatxas a constant and only worry about the other number.The other number is not constant, so you need a function, not just a simple expression. Haskell provides “operator sections” to do this with infix operators like
(*), so usingxwe get(x *).Backing out the last few steps, you’re now giving
xa name, and creating a function, which you pass tomap…and you’re actually done at this point, if you want to be. But it might be clearer for a beginner to make the list an explicit argument:
Both forms do the same thing, though.