S
S
Sherzod2020-05-11 13:26:55
Haskell
Sherzod, 2020-05-11 13:26:55

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

1 answer(s)
R
Roman, 2020-05-11
@egnaf

Or so

λ> myfun = (^2)
λ> myfun <$> [1, 2, 3]
[1,4,9]

λ> myfun = (^2)
λ> map myfun [1, 2, 3]
[1,4,9]

What fits the definition better?

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

Although
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 question

Ask a Question

731 491 924 answers to any question