JavaScript To ELM conversion

Hello, I start learning ELM and i need help with syntax.
I write this javascript code and i want to convert it to ELM lang.
can anyone help me with that please

function computeNextValue (x){
list = numberToArray(x);
sum = add(list);
let y = x + sum;
return y;
}

function numberToArray(number) {
let array = number.toString().split("");//stringify the number, then make each digit an item in an array
return array.map(x => parseInt(x));//convert all the items back into numbers
}

function add(list){
let sum = 0;
for (var i = 0; i < list.length; i++) {
interm = parseInt(list[i]);
sum += interm;
}
return(sum);
}

computeNextValue : Int -> Int
computeNextValue x =
    let
        list =
            numberToArray x

        sum =
            List.foldl (+) 0 list
    in
    x + sum


numberToArray : Int -> List Int
numberToArray number =
    number
        |> String.fromInt
        |> String.split ""
        |> List.map (String.toInt >> Maybe.withDefault 0)

I guess something like this when trying to convert directly from js…
If I interpreted the functions correctly that is :slight_smile:
Here is a working ellie : https://ellie-app.com/dFzcGpMPWnKa1

computeNextValue : Int -> Int
computeNextValue x =
   List.sum (numberToList x) + x


numberToList : Int -> List Int
numberToList number =
    String.fromInt number -- convert our Int to a String
        |> String.split ""
        |> List.filterMap String.toInt -- String.toInt returns a Maybe Int so we use List.filterMap to filter out the Nothing cases, which should be none in this instance

This would do what you want. If you wanted to write add yourself you could do it as

add : List Int -> Int
add nums =
    List.foldl (\n sum -> n + sum) 0 nums
1 Like

thank you for your help !

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.