Printing 10 numbers in Haskell -



Printing 10 numbers in Haskell -

i have began larn haskell. experienced c, c++, java , php. still cant figure out how print numbers 0 10 in haskell whithout having putstrln on different lines.

in java, :

for(int i=0; i<=10; i++) system.out.println(i);

howver, haskell doesn't seem back upwards this. how can produce same result ?

i guess question boils downwards to: how loop in haskell?

and reply recurse. , because it's haskell, mutual kinds of recursions have idioms. can utilize ghci next examples.

here 2 mutual loop translation examples:

in c:

int a[10]; (i=0; i<10; i++) a[i] = i*i;

and in haskell:

a = map (\i -> i*i) [1..10]

which reads, apply function takes number , returns number multiplied itself, list of 10 numbers. technique called map.

or

a = [ i*i | <- [1..10] ]

which similar set-builder notation. technique called list comprehension.

their output:

[1,4,9,16,25,36,49,64,81,100]

here's one: c:

int = 1; (i=1; i<10; i++) = *i;

haskell:

foldl (\currentvalue -> currentvalue * i) 1 [1..10]

output:

3628800

and 1 above called folding.

now, you're doing printing screen. expect following:

map (\i -> putstrln (show i)) [1..10]

which reads, apply function prints "show" value of number onto list of numbers 1 10. since expression, output of line list of printing computations:

[ io(), io (), io() ]

this not easy type display, ghci returns error you.

for purposes, printing 10 values, need monadic map:

mapm (\i -> putstrln (show i)) [1..10]

or improve yet,

mapm_ (\i -> putstrln (show i)) [1..10]

why, , how happens more of foray io , monads.

haskell

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -