Created
February 9, 2013 22:32
-
-
Save WillNess/4747404 to your computer and use it in GitHub Desktop.
http://stackoverflow.com/q/14713387/849891 SquareNumbersList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http://stackoverflow.com/q/14713387/849891 | |
Write a recursive function squares that takes a list of integers, | |
and returns a list of the squares of those integers in haskell [closed] | |
up vote | |
-7 | |
down vote | |
favorite | |
1 | |
For example, squares [1,2,10] should evaluate to [1,4,100], while squares [] | |
should evaluate to []. Also try your function on an infinite list, for example | |
squares [1..] or squares [1,3..]. | |
----- | |
Here's what you could do: start typing what they say it must do: | |
fun [1,2,10] = [1,4,100] -- (1) | |
That's a perfectly valid Haskell code, a part of a Haskell function definition. | |
Why just a part? Because this function won't work with any other argument. But | |
they say it must also work with empty lists - so write down that rule too, | |
that the definition says our function must follow: | |
fun [] = [] -- (2) | |
Now it says, our function must work also with an infinite list [1..]. | |
Let's try to cook up something: | |
fun [1..] = ... ? -- (3) | |
Now we need to understand what is `[1..]`? It is a list. One thing we | |
know for sure, its first element is `1`: `(1:xs) = [1..]`. What would | |
be the first element of `xs`? `2`, right? So `[1..] == 1:[2..]` and we | |
can also write, instead of `(3)`, | |
fun (1:[2..]) = ys where -- and then what? -- (4) | |
(y:t) = ys -- what is the ys' frst element? | |
y = square 1 -- right? | |
and what about `t`? It is | |
t = fun [2..] -- d'oh | |
So, must we now write out also the rule for `fun [2..]`? | |
fun (2:[3..]) = ys where | |
y:t = ys | |
y = square 2 | |
t = fun [3..] | |
All perfectly valid Haskell, and following the specs fully so far. | |
So, must we write out the infinite spec in full, by hand? | |
Or can we use *variables*? | |
.... | |
end of part 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment