1

I came across this replicate function,

replicate' n x = [x|y <- [1..n]]

Why is y there? y is being assigned values from 1 to n despite not being featured in the output expression.

‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎

2
  • 1
    Because whoever wrote that code didn't know that you could put the wildcard pattern _ there. Having a y variable that's unused like that is just poor form. Commented Nov 5, 2022 at 1:40
  • You can also write fmap (const x) [1..n] or x <$ [1..n] Commented Nov 5, 2022 at 16:04

1 Answer 1

1

The idea is that the list comprehension:

[some_expr_involving_y | y <- [1..n]]

will produce a list of n elements that are the results of evaluating some_expr_involving_y with y set to each the numbers 1, 2, ... n in turn.

In the special case where some_expr_involving_y is just some constant x that doesn't depend on y, the result will be n copies of x, one for each (unused) value of y.

As pointed out in a comment, it may be better style to use a wildcard, as that's what it's for:

replicate' n x = [x | _ <- [1..n]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.