How to iterate using List.foreach and then add element in map?

I want to iterate through a list and for every address in the list i want to extract its client from the map and then assign it to new map. Sample is given below but it throws error as List.foreach requires unit function

 @compiler >= 4

include "List.aes"

contract User = 

    record state = { 
        owner               : address,
        default_client    : address,
        account_to_referrer : map(address, address),
        client_percentage : int
        }
  
    record clientList = {
        referres : map(address, address),
        client_percentage : int
        }

    stateful entrypoint init() = {
        owner = Call.caller,
        default_client = Call.caller,
        account_to_referrer = {},
        client_percentage = 1 }
    
    public stateful entrypoint getUserClient(users: list(address)) : clientList =
        let clientMapping : map (address, address) = {}

        List.foreach(users, (user) => clientMapping{user = Map.lookup_default(user, state.account_to_referrer, state.default_client) } ) //Line where error is produced
        let new_client_list : clientList = {
                client = clientMapping,
                client_percentage = state.client_percentage
            }
        new_client_list          

type_error: Cannot unify unit and map(address, address)
At: Line 28, column 9

3 Likes

List.foreach is when you are doing a side effect (like spend or state update) for each thing in the list. If you want to produce a value for each thing in the list (i.e. the end result should be another list) then you should use List.map

2 Likes