Last active
August 29, 2015 14:12
-
-
Save mashingan/563974c50b1f56d41475 to your computer and use it in GitHub Desktop.
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
package main | |
import "fmt" | |
func main() { | |
res := summedsquare(getInts(), 0) | |
if !(res <= 0) { | |
fmt.Println(res) | |
} | |
main() | |
} | |
/* | |
Function summedsquare: []int int -> int | |
Side-effect: None | |
Calculating the sum of each element squared using tail recursion. It | |
bypasses the negative value and proceed to sum next positive value squared. | |
It will return -1 if the length of integers array is 1 and the base | |
output is 0. | |
*/ | |
func summedsquare(arr []int, out int) int { | |
if len(arr) == 1 && out == 0 { | |
return -1 | |
} | |
if len(arr) == 0 { | |
return out | |
} else { | |
head, tail := arr[0], arr[1:] | |
if head < 0 { | |
head = 0 | |
} | |
return summedsquare(tail, out+head*head) | |
} | |
} | |
/* | |
Function getIntsAux: []int -> []int | |
Side-effect: None | |
Repeatedly scanning for an integer value recursively. Using newline to break | |
the recursive. Returns array of integers. | |
*/ | |
func getIntsAux(in []int) []int { | |
var temp int | |
_, err := fmt.Scanf("%d", &temp) | |
if err != nil { | |
return in | |
} | |
return getIntsAux(append(in, temp)) | |
} | |
/* | |
Function getInts: void -> []int | |
Side-effect: None | |
Wrapper for getIntsAux for scanning from the start (getIntsAux can be used | |
to continue the scanning of integers by supplying previous integers array). | |
Returns array of integers. | |
*/ | |
func getInts() []int { | |
return getIntsAux([]int{}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment