You can do this by looking at the window positions. Take "right" as an example.
If any window has a left column position greater than the current window's rightmost column, then the current window has some right neighbor. Think about this for a few minutes. Of course, you would need to write similar functions for the other cardinal directions.
let l:rightedge = win_screenpos(0) + winwidth(0) - 1
for l:win in range(1, winnr('$'))
if l:win != winnr() && win_screenpos(l:win) > l:rightedge
This solution is much more robust than any that switches windows, since window switching has unpredictable side-effects, even with
It will not tell you which window is to the immediate right, as defined by
wincmd l. In general this would also depend on the cursor position and row positions of the other windows. That is, a window may have many right neighbors but
wincmd l picks one.