Help with list in sophia


I am doing dacade tutorial, and I want to put all memes in list(meme)

But I am having problems retrieving the value from the list.

Here is my code

The error comes on line 20 but I am sure that there will be more errors :slight_smile:
Please help

1 Like

I think you mix up the concept of list and some sort of array. But that said you could implement it like this… Might be easier to use a map(int, meme) but that is up to you.

The following compiles, but I haven’t test it functionally:

include "List.aes"
payable contract MemeVote =

  record meme =
    { creatorAddress : address,
      url            : string,
      name           : string,
      voteCount      : int

  record state =
    { memes : list(meme),
      votes : map(int, int)

  entrypoint init() =
    { memes = [], votes = {} }

  entrypoint getMeme(index : int) : meme =
    List.get(index, state.memes)

  entrypoint getVote(index : int) : int =
    switch(Map.lookup(index, state.votes))
      None    => abort("There are no votes for meme with this index.")
      Some(x) => x

  stateful entrypoint registerMeme(url' : string, name' : string) =
    let meme = { creatorAddress = Call.caller, url = url', name = name', voteCount = 0}
    let newMemes = state.memes ++ [meme]
    put(state{ memes = newMemes })

  entrypoint getMemesLength() : int =

  payable stateful entrypoint voteMeme(index : int) =
    let meme = getMeme(index)
    Chain.spend(meme.creatorAddress, Call.value)
    let updatedVoteCount = meme.voteCount + Call.value
    put(state{ votes[index] = updatedVoteCount })

Thank you.

I wanted to make immutable list of memes that cannot be deleted. Figured a list should suit it fine

A list is not indexable. (Since it isn’t an array.) Hence the call to List.get which will be O(n) in the length of the list… But for smaller examples it wont be a problem.