Beginner / student implementation of foreach in haskell

I am trying to implement foreach morphism to test my understanding of morphism definition and pattern matching ... Obviously, I completely miss both points.

Could you fix me? I want morphism foreachtook a list aand a morphism fas an argument and returns a list of all the results rof f, applicable to all elements a.

foreach :: [a] β†’ f β†’ [r]
foreach [] f = []
foreach x:[] f = (f x):[]
foreach []:x f = []:(f x)
foreach (x:xs) f = (f x) : (foreach (xs f))

When compiling I have src\Main.hs:23:0: Parse error in pattern

+5
source share
3 answers

The problem is syntactic in this line:

foreach x:[] f = (f x):[]

The design application in templates should usually be enclosed in brackets. This will work:

foreach (x:[]) f = (f x):[]

, - , :

foreach (x:[]) f = f x:[]

, , , :

foreach [x] f = [f x]

, . :

foreach :: [a] β†’ f β†’ [r]

, f. , a -> r.

foreach x:[] f = (f x):[]

- , f to x , .

foreach []:x f = []:(f x)

, , , - , [], , .

foreach (x:xs) f = (f x) : (foreach (xs f))

, . -, , :. , (xs f) xs f, . foreach , foreach xs f.


(, ) map:

map :: (a -> b) -> [a] -> [b]
map _ []     = []
map f (x:xs) = f x : map f xs
+12

, , ( , Haskell) . , a f r. : " . ".

, - map:

map :: (a -> b) -> [a] -> [b]

, , :

foreach :: [a] -> (a -> b) -> [b]

, .

- , , . :, "cons", (, 1 : [2,3,4]). , []:(f x). ++, (, [f x] ++ xs, (f x) : xs), foreach.

, (foreach (xs f)) , . foreach(xs,f) C-, foreach(xs(f)). (xs f), , xs f . (foreach xs f).

, . : , , (f x) : (foreach xs f) f x : foreach xs f.

+3

You forgot to put ()in foreach []:x f = []:(f x)and incorrectly specified the type of function, now you need to compile the following:

foreach :: [a] -> (a -> r) -> [r]
foreach [] f = []
foreach (x:[]) f = (f x):[]
foreach (x:xs) f = (f x) : (foreach xs f)

and run:

*Main> foreach [1..20] (+1)
[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
+2
source

All Articles