Answer the question
In order to leave comments, you need to log in
How to call a function on all elements of a list in Haskell?
Hello.
Let's say I have a list like this:
And there is a function: How to call a function on all elements of a list in Haskell?
Java example:
[1, 2, 3, 4, 5]
pow2 x = x ^ 2
for (Integer i : list) {
pow2(i);
}
Answer the question
In order to leave comments, you need to log in
Or so
λ> myfun = (^2)
λ> myfun <$> [1, 2, 3]
[1,4,9]
λ> myfun = (^2)
λ> map myfun [1, 2, 3]
[1,4,9]
There is a function:
pow2 x = x^2
There is such a list:
[1, 2, 3, 4, 5]
How to call a function on all elements of a list
squares :: Num a => [a] -> [a]
squares lst = do
x <- lst
return (x ^ 2)
squares' :: Num a => [a] -> [a]
squares' lst = lst >>= \x -> return (x ^ 2)
squares'' :: Num a => [a] -> [a]
squares'' lst = [x ^ 2 | x <- lst]
fx f lst = [f x | x <- lst]
main = do
print $ fx (^2) [1, 2, 3]
print $ squares [1, 2, 3]
print $ squares' [1, 2, 3]
print $ squares'' [1, 2, 3]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question